'infer values from objects using object keys
Been looking for an answer for this, but couldn't find an exact one.
I have to following code example:
interface RowData {
firstName: string;
lastName: string;
age: number;
participate: boolean;
}
const rows: RowData[] = [
{
firstName: 'John',
lastName: 'Dou',
age: 0,
participate: true
}
]
function mapRowsData(key: keyof RowData, rowData: RowData) {
let value = rowData[key];
switch(key) {
case 'firstName': {
return value.toUpperCase(); // error 1
}
case 'age': {
return value * 2; // error 2
}
default: {
return '-'
}
}
}
The errors are of the same type:
error1:
Property 'toUpperCase' does not exist on type 'string | number | boolean'.
Property 'toUpperCase' does not exist on type 'number'.(2339)
error2:
The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type.(2362)
What's a simple way to make the inference work and identify the value's type according to key? Appreciate.
Solution 1:[1]
I tried using type inference similar to this answer, but was still getting the same errors as you. As an alternative approach, you could use the key directly in the case statement:
function mapRowsData(key: keyof RowData, rowData: RowData) {
switch(key) {
case 'firstName': {
return rowData.firstName.toUpperCase();
}
case 'age': {
return rowData.age * 2;
}
default: {
return '-'
}
}
}
You could also cast to the expected key type like so:
function mapRowsData(key: keyof RowData, rowData: RowData) {
let value = rowData[key];
switch(key) {
case 'firstName': {
return (value as string).toUpperCase();
}
case 'age': {
return (value as number) * 2;
}
default: {
return '-'
}
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
