我有一个简单的函数,它在参数中接受一个对象。为了仅接收有效数据,我需要输入对象的键,如下所示:
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]但打字就没用了。
我希望定义一个type可以只有一个键的对象。
这是一个尝试:
type OneKey<K extends string> = Record<K, any>
Run Code Online (Sandbox Code Playgroud)
不幸的是,这并不完全有效,因为变量可以具有联合类型:
type OneKey<K extends string> = Record<K, any>
declare function create<
K extends string,
T extends OneKey<K>[K]
>(s: K): OneKey<K>
const a = "a";
const res = create(a);
// Good
const check: typeof res = { a: 1, b: 2 }
// ~~ Error, object may only specify known properties
declare const many: "a" | "b";
const res2 = create(many);
// **Bad**: I only want one key
const check2: …Run Code Online (Sandbox Code Playgroud)