In a previous question, I asked about assigning a value of a object and the key of an object. Now that I have implemented it, the first function works fine when using the keyof
but the second does not let me switch on the key
to narrow down the type.
Below is example code that has comments next to the relevant lines.
type JWT = { id: string, token: string, expire: Date };
const obj: JWT = { id: 'abc123', token: 'tk01', expire: new Date(2018, 2, 14) };
function print(key: keyof JWT) {
switch (key) {
case 'id':
case 'token':
console.log(obj[key].toUpperCase());
break;
case 'expire':
console.log(obj[key].toISOString()); // Works!
break;
}
}
function onChange<K extends keyof JWT>(key: K, value: JWT[K]) {
switch (key) {
case 'id':
case 'token':
obj[key] = value + ' (assigned)';
break;
case 'expire':
obj[key] = value.toISOString(); // Error!
break;
}
}
How can I implement the onChange
function so that switch will narrow down the type similar to the print
function above?