3

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.

1
  • unfortunately no as it will make type unsafe Commented May 22, 2017 at 16:31

1 Answer 1

5

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'
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.