Lhew
Lhew

Reputation: 624

Creating an interface by extracting types from an interface

I have the following interface:

interface FooBar {
    foo: string;
    bar: number; 
}

Is there a way to, dynamically, creates a type that accepts 'foo' or 'bar'?

like:


const update = (obj: FooBar, key: string, value: string | number) => {
   ...
}

In this case, instead of string | number, I would like to extract the values from FooBar so I don't have to update two places at once

Any ideas? Thanks so far

Upvotes: 0

Views: 33

Answers (1)

ccarton
ccarton

Reputation: 3666

You can make the key type a generic parameter and then index the interface:

function update<K extends keyof FooBar> (obj: FooBar, key: K, value: FooBar[K]) {
  obj[key] = value
}

update(obj, 'bar', 10) // OK
update(obj, 'foo', 'x') // OK

update(obj, 'foo', 10) // Error
// --------------> ~~ 
// Argument of type 'number' is not assignable to parameter of type 'string'.

Upvotes: 3

Related Questions