Hans Yulian
Hans Yulian

Reputation: 1180

Object setter function that checks the value based on key

For example i have an object like this:

interface Test{
   a: number;
   b: string;
   c: boolean;
}

const obj:Test = {
   a: 1,
   b: '1',
   c: true,
}

I want to make a function that can change the content of the object, but the value is checked based on the key. I can get the getter like this, but i'm stuck in making the setter:


function getValue<T , U = keyof T>(obj: T, key: U){
   return obj[key]
}

function setValue<T , U = keyof T, V???????>(obj: T, key: U, value: V>{
   obj[key] = value
}

So that if i do:

setValue(obj,'a',1) // no error
setValue(obj,'b',1) // typecheck error

Upvotes: 1

Views: 82

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370799

You don't need a third generic - you can just use T[U], since both T and U are defined by that point.

function getValue<T, U extends keyof T>(obj: T, key: U){
   return obj[key]
}

function setValue<T, U extends keyof T>(obj: T, key: U, value: T[U]){
   obj[key] = value
}

setValue(obj,'a',1) // no error
setValue(obj,'b',1) // typecheck error

Upvotes: 2

Related Questions