Ky6uk
Ky6uk

Reputation: 1223

How to bound types inside function arguments

Is it possible to check types of an one argument based on an other argument in functions? There is an example:

interface Data {
  id?: number;
  name?: string;
}

let data : Data = {};

// have no idea how to strict "value" argument
function update(field : keyof Data, value) {
  data[field] = value;
}

update('id', 0);             // [1] ok
update('name', 'foo');       // [2] ok
update('id', 'some string'); // [3] FAIL ("id" must be a number)
update('name', 123);         // [4] FAIL ("name" must be a string)
update('other', 123);        // [5] FAIL ("other" isn't possible argument)

I am not sure it is possible to do that way. In the example only call number [5] will fail.

Upvotes: 1

Views: 42

Answers (1)

jmattheis
jmattheis

Reputation: 11115

Add a generic which can be any key of Data and then get the type of K with Data[K].

function update<K extends keyof Data>(field: K, value: Data[K]) {
   data[field] = value;
}

with this 1 and 2 compile and 3, 4 and 5 throw a compile error.

Upvotes: 3

Related Questions