方括号表示字段在打字稿中的位置是什么意思?

tri*_*587 18 typescript

我在三个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)

  • @FernandoGabrieli 是的,据我所知,你是对的。你可以在那里使用任何东西。我总是使用“索引”,因为我认为这样更清楚。但是,是的,你可以使用任何东西,但我不知道它会带来什么真正的不同。事实上,如果您查看编译器生成的 javascript,您会发现当您更改该属性名称时,它不会发生变化。 (2认同)

小智 5

括号声明一个索引签名,这意味着除了强制类型之外,您可以将任何内容放入第一个参数中。

基本上这削弱了参数的类型安全性。如果该函数本身不是消费者,而是使用更强类型的玩家之间的通用互连(他们将对事件结构有更深入的了解),那么这种机制非常有用。

我添加了另一个答案,因为现有答案将其命名为可选参数,但事实并非如此。可选参数后缀为“?” 并且完全不同。