[英]How to type an object key in Typescript?
I have a simple function that takes an object in parameter.我有一个简单的 function 在参数中采用 object。 In order to receive only valid data, I need to type the key of the object as such:
为了只接收有效数据,我需要输入 object 的密钥,如下所示:
type DataType = "about" | "favorites" | "username"; type UpdatedData = { [key in DataType]: any }; function onSave (updatedData: UpdatedData){ //do stuff } // in a component const onClickSave = () => onSave({ "about": text });
Typescript throws the following error: Typescript 抛出以下错误:
Argument of type '{ about: text;
'{ about: text; 类型的参数}' is not assignable to parameter of type 'UpdatedData'.
}' 不可分配给“UpdatedData”类型的参数。 Type '{ about: text;
输入'{关于:文本; }' is missing the following properties from type 'UpdatedData': favorites, username
}' 缺少“UpdatedData”类型的以下属性:收藏夹、用户名
How to fix this?如何解决这个问题? Of course, I could write
[key: string]
instead of [key in DataType]
but the typing would be useless then.当然,我可以写
[key: string]
而不是[key in DataType]
,但这样打字就没用了。
As the properties of UpdatedData
can be optional just add in a ?
由于
UpdatedData
的属性可以是可选的,只需添加?
to make them optional.使它们成为可选的。
Edit: As @Jérémie B mentioned an empty {}
is still permitted with this.编辑:正如@Jérémie B 提到的那样,仍然允许使用空的
{}
。
type DataType = "about" | "favorites" | "username";
type UpdatedData = { [key in DataType]?: any };
function onSave (updatedData: UpdatedData){
}
const text = "hello"
const onClickSave = () => onSave({ "about": text });
try this:尝试这个:
type DataType = "about" | "favorites" | "username";
type Expand<U> = U extends string ? { [key in U]: any } : never
type UpdatedData = Expand<DataType>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.