TypeScript接口字符串属性的默认值

Har*_*lue 6 typescript

我有一个看起来像这样的界面

export interface IAppSection {
  key: string;
  order: number;
  header: string;
  content: string;
  modifiedAt: string;
  modifiedByEmployeeId: number;
  change: 'added' | 'removed' | 'updated' | 'none';
}
Run Code Online (Sandbox Code Playgroud)

我想做的是在存储与该接口相关的对象时使用change默认值none

我已经尝试过了,change: 'added' | 'removed' | 'updated' | 'none' = 'none'但这不起作用。

我敢肯定,我在这里做错了什么,对于我如何实现这一目标,我将不胜感激。

Tit*_*mir 9

你不能用接口来做到这一点。接口在运行时完全擦除,不会影响运行时行为;这是设计使然。您可以改为创建一个类并为该字段分配一个默认值,或者您可以创建一个将分配默认值的函数。

我们甚至可以构造一个函数来帮助我们使用默认值创建这样的函数:

interface IAppSection {
  key: string;
  order: number;
  header: string;
  content: string;
  modifiedAt: string;
  modifiedByEmployeeId: number;
  change: 'added' | 'removed' | 'updated' | 'none';
}

function withDefaults<T>() {
  return function <TDefaults extends Partial<T>>(defs: TDefaults) {
    return function (p: Pick<T, Exclude<keyof T, keyof TDefaults>> & Partial<TDefaults>) :T {
      let result: any = p;
      for (let k of Object.keys(defs)) {
        result[k] = result[k] || defs[k];
      }
      return result;
    }
  }
}

const appSection = withDefaults<IAppSection>()({
  change: 'none'
})
Run Code Online (Sandbox Code Playgroud)


zer*_*ewl 0

您不能在接口中设置默认值,只能在实现中设置。

但默认情况下它们是未定义的,这基本上就可以了。

对于“真正的”实现,您的字符串联合看起来不错。

另请参阅: Typescript 界面默认值