【问题标题】:TypeScript interface default value on string property字符串属性的 TypeScript 接口默认值
【发布时间】:2018-12-13 18:30:14
【问题描述】:

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

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

我想做的是在存储此接口相关的对象时将change 默认为none

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

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

【问题讨论】:

  • 我不认为,这在interface 中是可能的。虽然您可以在其constructor 中从已实现的类中初始化默认值。

标签: typescript


【解决方案1】:

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

但默认情况下,它们是 undefined,这几乎没问题。

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

另请参阅: Typescript interface default values

【讨论】:

    【解决方案2】:

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

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

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

    【讨论】:

    • 但是这个方法也可以处理默认的嵌套对象赋值吗?
    • 不确定我做错了什么,但withDefaults()() 为我返回了一个函数
    【解决方案3】:

    另一种处理方式是将所有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'
           }
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-05-06
      • 1970-01-01
      • 2014-03-24
      • 2021-05-10
      • 1970-01-01
      • 2018-07-14
      • 1970-01-01
      • 2020-09-18
      相关资源
      最近更新 更多