Issue
Code like this I want to set the object value with key, the key param of function setObjKeyValue is one of the key of obj, and the type of the value param is correspondingly the value of the key. But I have no idea how to define the value type. I think Generic probably sovely my problem, could anyone give me some tips?
interface Obj {
foo: number,
bar: string
}
const obj: Obj = {
foo: 2333,
bar: 'fff'
}
function setObjKeyValue(key: keyof Obj, value):Obj {
obj[key] = value
return obj
}
Solution
Yes. To do it, you have to ensure that value has the correct type by declaring the key type as a generic, using that key type for key, and then using Obj[KeyType] as the type of value. That way, TypeScript knows the specific value to use for value rather than inferring string | number.
interface Obj {
foo: number,
bar: string
}
const obj: Obj = {
foo: 2333,
bar: 'fff'
};
function setObjKeyValue<KeyType extends keyof Obj>(key: KeyType, value: Obj[KeyType]): Obj {
obj[key] = value;
return obj;
}
It seems a bit odd that setObjKeyValue uses the obj that it closes over though. You might want to pass obj as a parameter as well:
function setObjKeyValue<ObjType extends Obj, KeyType extends keyof ObjType>(
obj: ObjType,
key: KeyType,
value: ObjType[KeyType]
): ObjType {
obj[key] = value;
return obj;
}
Answered By - T.J. Crowder
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.