![](/img/trans.png)
[英]How to define type as a list of object keys defined like [key: string] key/value structure - TypeScript
[英]How to define Object Key as String Type
下面是功能签名,
export function getVideoBooleansParamsString(videoBooleans: {
string: { label: string; value: boolean }
}): string {}
这是arg
我试图进入,
const videoBooleans = { video: { label: 'video', value: true } }
并产生以下错误,
(63,33): error TS2345: Argument of type '{ exchange: { filterType: string; filterValues: string[]; }; }' is not assignable to parameter of type '{string: FilterModel; }'.
Property 'string' is missing in type '{ exchange: { filterType: string; filterValues: string[]; }; }'.
我打算声明的是一个对象,无论键是具有{ label: string; value: boolean }
{ label: string; value: boolean }
您定义它的方式现在期望以下内容:
const videoBooleans = { string: { label: 'video', value: true } };
getVideoBooleansParamsString(videoBooleans);
如果希望键为任何字符串,则可以这样定义:
export function getVideoBooleansParamsString(videoBooleans: {
[key: string]: { label: string; value: boolean }
}): string { }
或更像这样,更具体地说:
export function getVideoBooleansParamsString(videoBooleans: {
video: { label: string; value: boolean }
}): string { }
您还可以定义一个接口,该接口可以使函数签名更简洁:
interface MyVideoType {
[key: string]: { label: string, value: true };
}
export function getVideoBooleansParamsString(videoBooleans: MyVideoType): string { }
const video: MyVideoType = { video: { label: 'video', value: true } };
getVideoBooleansParamsString(video);
您需要为参数类型定义一个索引:
export function getVideoBooleansParamsString(videoBooleans: {
[name :string] : { label: string; value: boolean }
}): string {}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.