I would like to use object literal instead of switch statement, but i got this error:
Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ apple: string[]; orange: string[]; watermelon: string[]; default: void; }'. No index signature with a parameter of type 'string' was found on type '{ apple: string[]; orange: string[]; watermelon: string[]; default: void;}' ts(7053)*
SWITCH STATEMENT
const fruits = (fruit: string): string[] => {
switch (fruit) {
case 'apple': {
return state.apple;
}
case 'orange': {
return state.orange;
}
case 'watermelon': {
return state.watermelon;
}
default: {
return ('Not found');
}
}
};
OBJECT LITERAL
const fruits = (fruit: string): string[] => {
const fruitCategory = {
apple: state.apple,
orange: state.orange,
watermelon: state.watermelon,
default: 'Not Found',
};
return fruitCategory[fruit] ?? fruitCategory.default;
CodePudding user response:
You could give your fruitCategory
object an index signature to indicate that it can be indexed by any string
value.
const fruits = (fruit: string): string[] => {
const fruitCategory: Record<string, string[]> = {
apple: state.apple,
orange: state.orange,
watermelon: state.watermelon,
default: ['Not Found'],
};
return fruitCategory[fruit] ?? fruitCategory.default;
}
Note that you default
"branch" should also return a string[]
.