Don*_*al0 8 javascript typescript reactjs
我有一个简单的函数,它在参数中接受一个对象。为了仅接收有效数据,我需要输入对象的键,如下所示:
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 });Run Code Online (Sandbox Code Playgroud)
打字稿抛出以下错误:
'{ about: text; 类型的参数 }' 不可分配给“UpdatedData”类型的参数。输入 '{ 关于:文本;}' 缺少类型“UpdatedData”中的以下属性:收藏夹、用户名
如何解决这个问题?当然,我可以写[key: string],[key in DataType]但打字就没用了。
yud*_*esh 10
由于 的属性UpdatedData可以是可选的,只需添加 a?即可使其可选。
编辑: \n正如 @J\xc3\xa9r\xc3\xa9mie B 提到的那样,{}仍然允许使用空值。
type DataType = "about" | "favorites" | "username";\ntype UpdatedData = { [key in DataType]?: any };\nfunction onSave (updatedData: UpdatedData){\n}\nconst text = "hello"\n\nconst onClickSave = () => onSave({ "about": text });\nRun Code Online (Sandbox Code Playgroud)\n
| 归档时间: |
|
| 查看次数: |
8061 次 |
| 最近记录: |