TypeScript中接口中方括号内的字段是什么

can*_*stu 3 typescript

export interface Principal {
  name: string; // just a field
  [attribute: string]: any; // allowed custom fields

  [securityId]: string; // what does this mean ?
}
Run Code Online (Sandbox Code Playgroud)

securityId 是什么意思?

Kot*_*lar 6

securityId 是一个计算属性名称。

要使此代码编译,securityId必须是类型限制为文字字符串或唯一符号类型的值。

例如:

const securityId: "security" = "security";

interface Principal {
    [securityId]: string;
}
Run Code Online (Sandbox Code Playgroud)

指定名为 的属性security

如果securityId没有文字类型,这将是一个错误:

const securityId: string = "security";

interface Principal {
    // ERROR: A computed property name in an interface must refer to an
    // expression whose type is a literal type or a 'unique symbol' type.
    [securityId]: string;
}
Run Code Online (Sandbox Code Playgroud)

注意:我试图在规范中找到对这种行为的引用,但它似乎已经过时而不是优先考虑- 欢迎编辑!