Can you validate types of one argument based on another argument in functions? Consider this example:
interface Data {
id?: number;
name?: string;
}
let data : Data = {};
// I am unsure how to make the "value" argument strict
function update(field : keyof Data, value) {
data[field] = value;
}
update('id', 0); // [1] success
update('name', 'foo'); // [2] success
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" is not a valid argument)
I am uncertain if it is achievable in this way. In the provided example, only call number [5]
will result in failure.