How to dynamically access object property in TypeScript

"OK" is a string, and str is implicitly taking the type string in your code.

When you try to access an object’s property, you need to use a type keyof. TypeScript then knows you are not assigning a random string; you are assigning strings compatible with the properties (keys) for the object.

Also, since status is a variable, not a type, you need to extract its type with typeof.

Try:

let str = "OK" as keyof typeof status;
status[str]; // 200

or more cleanly:

type StatusKey = keyof typeof status;
let str: StatusKey = "OK";
status[str]; // 200

// and to answer the question about reversal
status[status.OK as StatusKey]; // OK

See: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-1.html#keyof-and-lookup-types

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)