我在三分钟内遇到了这条线.d、 ts:

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

and was wondering what it meant.
I understand that this would mean a function called dispatchEvent which takes an argument of a type with a member type but I am not sure what:

[attachment: string]: any;

方法

推荐答案

这是一个索引签名.从TypeScript documentation:

可索引类型有一个索引签名,它描述了我们可以用来索引到对象中的类型,以及索引时相应的返回类型.

例如,您可以为可转位对象定义一个接口,如:

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; [attachment: string]: any; }类型的参数.

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

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相关问答推荐

返回签名与其他类型正确的函数不同的函数

类型脚本:类型是通用的,只能索引以供阅读.(2862)"

如何在ts中使用函数重载推断参数类型

是否可以根据嵌套属性来更改接口中属性的类型?

如何根据另一个属性的布尔值来缩小函数属性的返回类型?

返回同时具有固定键和变量键的对象的函数的返回类型

Vue SFC中的多个脚本块共享导入的符号

用于验证字符串变量的接口成员

使用KeyOf和Never的循环引用

为什么我的动画状态在组件实例之间共享?

TYPE FOR ARRAY,其中每个泛型元素是单独的键类型对,然后在该数组上循环

错误:NG02200:找不到类型为';对象';的其他支持对象';[对象对象]';.例如数组

如何使用TypeScrip在EXPO路由链路组件中使用动态路由?

编剧- Select 动态下拉选项

TypeScrip:从嵌套的对象值创建新类型

类型脚本中参数为`T`和`t|unfined`的重载函数

作为参数的KeyOf变量的类型

类型判断数组或对象的isEmpty

Route.ts文件中未导出HTTP方法

Next 13 + React 18 createContext 类型的构建问题