简体   繁体   中英

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.

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'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM