我在 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/