1

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
}

1 Answer 1

1

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;
}

Playground link

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;
}

Playground link

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.