Doua Beri
Doua Beri

Reputation: 10949

Typescript: string literal types from interface parameters

Let say I have an interface like this

interface I{
  id: string;
  name: string;
  age: number;
}

and a method like this

var obj:I={
      id: 'abc',
      name: 'Jim',
      age: 23
};
changeProperty(name:string, value:any){
   obj[name] = value;
}

Is there a way to declare the name parameter type to match interface fields?

One solution would be something like this

changeProperty(name: 'id' | 'name' | 'age' , value:any)

but in a much larger project where an interface can have 20+ fields it's much harder to maintain this.

Upvotes: 3

Views: 451

Answers (1)

artem
artem

Reputation: 51629

Yes, as described in the example for keyof and lookup types:

function changeProperty<N extends keyof I>(name: N, value: I[N]){
   obj[name] = value;
}

changeProperty('id', '123'); // ok
changeProperty('age', 53); // ok
changeProperty('name', 1); // Argument of type '1' is not assignable to parameter of type 'string'

Upvotes: 5

Related Questions