我在三个d.ts中遇到过这一行:
dispatchEvent(event: { type: string; [attachment: string]: any; }): void;
Run Code Online (Sandbox Code Playgroud)
并且想知道这意味着什么.
我理解这意味着一个名为dispatchEvent的函数,它接受一个带有成员类型的类型的参数,但我不确定:
[attachment: string]: any;
Run Code Online (Sandbox Code Playgroud)
手段.
Sea*_*mus 29
这是一个索引签名.从TypeScript 文档:
索引的类型有描述,我们可以使用索引到的对象的类型,与相应的返回类型索引时沿指数的签名.
因此,例如,您可以为可索引对象定义接口,如:
interface IArrayOfStrings {
[index: number]: string;
}
Run Code Online (Sandbox Code Playgroud)
这告诉编译器,对于任何类型的对象,IArrayOfStrings由数字索引访问的任何成员都是类型string.
所以,这将编译没有错误:
interface IArrayOfStrings {
[index: number]: string;
}
let words: IArrayOfStrings = ["foo","bar"];
let word: string = words[0];
Run Code Online (Sandbox Code Playgroud)
但这不会:
interface IArrayOfStrings {
[index: number]: string;
}
let words: IArrayOfStrings = ["foo","bar"];
let myNumber: number = words[0];
Run Code Online (Sandbox Code Playgroud)
在您的示例中,此行:
dispatchEvent(event: { type: string; [attachment: string]: any; }): void;
Run Code Online (Sandbox Code Playgroud)
描述了一个dispatchEvent接受一个类型参数的方法{ type: string; [attachment: string]: any; }.
要使该类型更易于理解,请查看定义此类型的接口:
interface IEvent {
type: string;
[attachment: string]: any;
}
Run Code Online (Sandbox Code Playgroud)
这告诉编译器类型的对象IEvent将具有被调用的字符串属性type,并且IEvent由字符串索引访问的对象的元素将是any类型.
所以,像这样的东西会编译没有错误:
interface IEvent {
type: string;
[attachment: string]: any;
}
let myEvent: IEvent = {
type: 'some-event-type'
};
let eventType: string = myEvent["type"];
Run Code Online (Sandbox Code Playgroud)
小智 5
括号声明一个索引签名,这意味着除了强制类型之外,您可以将任何内容放入第一个参数中。
基本上这削弱了参数的类型安全性。如果该函数本身不是消费者,而是使用更强类型的玩家之间的通用互连(他们将对事件结构有更深入的了解),那么这种机制非常有用。
我添加了另一个答案,因为现有答案将其命名为可选参数,但事实并非如此。可选参数后缀为“?” 并且完全不同。
| 归档时间: |
|
| 查看次数: |
7426 次 |
| 最近记录: |