【问题标题】:How to generalize all object properties except some?如何概括除一些之外的所有对象属性?
【发布时间】:2018-03-19 07:11:28
【问题描述】:

我希望所有属性都具有某种类型,但我希望显式声明的属性覆盖它:

interface Potato {
  a: number
  [all:string]: string
}

【问题讨论】:

    标签: typescript types typescript2.0


    【解决方案1】:

    您可以使用intersection types

    type PotatoAll = { [all: string]: string };
    type Potato = PotatoAll & { a: number };
    
    let p = {} as Potato;
    
    p['foo'] = 'foo';
    p.a = 1;
    p['a'] = 1;
    
    p['foo'] = 1; //error
    p['a'] = 'a'; //error
    p.a = 'a'; //error
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多