typescript - 方括号是什么意思,字段应该在 typescript 中的位置?

标签 typescript

我在 three.d.ts 中遇到了这条线:

dispatchEvent(event: { type: string; [attachment: string]: any; }): void;

想知道这是什么意思。
我知道这意味着一个名为 dispatchEvent 的函数接受一个带有成员类型的类型的参数,但我不确定是什么:

[attachment: string]: any;

表示。

最佳答案

那是一个索引签名。来自 TypeScript documentation :

Indexable types have an index signature that describes the types we can use to index into the object, along with the corresponding return types when indexing.

因此,例如,您可以为可索引对象定义一个接口(interface),例如:

interface IArrayOfStrings {
    [index: number]: string;
}

这告诉编译器,对于 IArrayOfStrings 类型的任何对象,数字索引访问的任何成员都将是 string 类型。

所以,这将编译没有错误:

interface IArrayOfStrings {
    [index: number]: string;
}

let words: IArrayOfStrings = ["foo","bar"];

let word: string = words[0];

但这不会:

interface IArrayOfStrings {
    [index: number]: string;
}

let words: IArrayOfStrings = ["foo","bar"];

let myNumber: number = words[0];

在您的示例中,这一行:

dispatchEvent(event: { type: string; [attachment: string]: any; }): void;

正在描述一种方法dispatchEvent,它接受一个类型的参数{ type: string; [附件:字符串]:任意;

为了使该类型更容易理解,请查看定义该类型的接口(interface):

interface IEvent {
    type: string;
    [attachment: string]: any;
}

这告诉编译器 IEvent 类型的对象将有一个名为 type 的字符串属性,以及 IEvent 对象的元素,通过字符串索引将是 any 类型。

所以,像这样的东西可以编译而不会出错:

interface IEvent {
    type: string;
    [attachment: string]: any;
}

let myEvent: IEvent = {
    type: 'some-event-type'
};

let eventType: string = myEvent["type"];

关于typescript - 方括号是什么意思,字段应该在 typescript 中的位置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38404400/

相关文章:

javascript - 使用 AMD 模块时,避免在 Typescript 中重复引用/导入外部 javascript 库

c# - 使用 SignalR 找不到名称为 'x' 的客户端方法

javascript - 如何比较具有不同字段的 2 个不同对象,并使用告诉共同元素的新字段创建一个新对象

javascript - 是否可以解构为已声明的变量?

javascript - *ngIf 密码验证不起作用 Angular 5

Typescript:获取类型的第一个属性的类型

typescript - 使用绑定(bind)时强制输入

reactjs - 何时使用 React.PropsWithChildren

TypeScript:自动完成但禁用推断

typescript - Vue CLI 的类型检查服务忽略内存限制