简体   繁体   English

如何区分打字稿索引签名和JS计算的属性名称

[英]How to distinguish between typescript Index signature and JS Computed Property Names

ngOnChanges(changes: {[propName: string]: SimpleChange}): void {
    console.log('Changes', changes);
  }

What does 'changes: {[propName: string]: SimpleChange}' do? “更改:{[propName:string]:SimpleChange}”有什么作用? I'm a little confused between when it is an indexable object or Computed Property Names. 在它是可索引对象还是计算属性名称之间,我有些困惑。

{[propName: string]: SimpleChange} is just an index signature, it does not have anything to do with computed properties. {[propName: string]: SimpleChange}只是一个索引签名,它与计算属性无关。

Computed properties occur in object literals and, depending on the computed property, typescript will either infer a computed property (if the property is a literal type) or an index signature (if the property is a property key base type): 计算的属性出现在对象文字中,并且取决于所计算的属性,typescript会推断一个已计算的属性(如果该属性是文字类型)或一个索引签名(如果该属性是属性键基本类型):

let propName = "a"; // string 
let o = { [propName] : 10 } // {[x: string]: number;}
o["A"] // ok

const constPropName = "a"; // "a"
let o2 = { [constPropName] : 10 } // {[constPropName]: number;}
o2["A"] //err

You can also declare an object type with a computed property explicitly, but the property must be a string, number or symbol literal type: 您还可以显式地声明具有计算属性的对象类型,但是该属性必须是字符串,数字或符号文字类型:

const constPropName = "a"; // "a"
type computed = { [constPropName] : number }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM