When utilizing Computed Property in javascript, I can structure my code as follows
const default_values = {a:"debug",b:"info",c:"warning"};
function execute(y) {
let x = default_values[y] || default_values.a /* if y is not a or b or c */
}
However, how can I achieve the same functionality in TypeScript ?
const default_values = {a:"debug",b:"info",c:"warning"};
function execute(y: string) {
let x = default_values[y] || default_values.a;
}
I encountered an error during compilation
error TS7053: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ a: string; b: string; c: string; }'.
No index signature with a parameter of type 'string' was found on type '{ a: string; b: string; c: string; }'.
I have tried searching SO but could not find a relevant answer, except for How to set a variable if undefined in typescript?, which is not applicable to my issue
Therefore, I updated my ts code to the following, although it seems more cumbersome compared to the original js code
function execute(y: string) {
let x:string
if (y!='a' && y!='b' && y!='c') {
x = default_values.a;
} else {
x = default_values[y]
}
}
---- update ----
@captain-yossarian provided one solution, e.g.
const default_values: Record<string, string> = { a: "debug", b: "info", c: "warning" };
Another method to resolve the issue is by using keyof typeof
, refer here https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-1.html#keyof-and-lookup-types for additional details, e.g. "In JavaScript it is fairly common to have APIs that expect property names as parameters, but so far it hasn’t been possible to express the type relationships that occur in those APIs.", precisely reflecting my scenario here!!
const default_values = {a:"debug",b:"info",c:"warning"};
function execute(y:keyof typeof default_values) {
let x = default_values[y] || default_values.a;
}
This solution was derived from How to dynamically access object property in TypeScript