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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/51188511/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 05:31:10  来源:igfitidea点击:

TypeScript interface default value on string property

typescript

提问by Harry Blue

I have an interface that looks like this

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

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

What I'd like to do is have changedefault as nonewhen the object this interface relates to is stored.

我想要做的是在存储与此接口相关的对象时具有change默认值none

I have tried change: 'added' | 'removed' | 'updated' | 'none' = 'none'but this does not work.

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

I am sure I am doing something wrong here and would really appreciate some feedback on how I can achieve this.

我确信我在这里做错了,非常感谢一些关于我如何实现这一目标的反馈。

回答by Titian Cernicova-Dragomir

You can't do this with interfaces. Interfaces are completely erased at runtime and can't impact runtime behavior, this is by design. You cand create a class instead and assign a default values to the field, or you can create a function that will assign the defaults.

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

We could even construct a function that helps us create such functions with defaults :

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

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'
})

回答by Gio

Another way to deal with is marking all IAppSectionvalues as required, and then use factory methods to create the IAppSectionobjects, inside the factory method you can ensure that all invariants are meet and assign default values for the optional arguments, per instance

另一种处理方法是将所有IAppSection值标记为需要,然后使用工厂方法创建IAppSection对象,在工厂方法中您可以确保所有不变量都满足并为每个实例为可选参数分配默认值

    const createAppSection = (
      key: string,
      order: number,
      header: string,
      content: string,
      modifiedAt: string,
      modifiedByEmployeeId: number,
      change?: 'added' | 'removed' | 'updated' | 'none';
    ) : IAppSection => {
       // perform invariants validations 
       if(!key){
         throw Error('key required');
       }
       return {
         key, order, content, modifiedAt, modifiedByEmployeeId,
         change: change || 'none'
       }
    }

回答by zerocewl

You can't set the default value in the interface, only in the implementation.

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

But by default they are undefinedwhich is mostly just fine.

但是默认情况下它们是未定义的,这通常很好。

For the 'real' implementation your string union looks good.

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

See also: Typescript interface default values

另请参阅: Typescript 接口默认值