"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
Answer from Guillaume F. on Stack Overflow"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
const obj = {
name: 'Bobby Hadz',
country: 'Chile',
};
// 👇️ type ObjectKey = "name" | "country"
type ObjectKey = keyof typeof obj;
const myVar = 'name' as ObjectKey;
console.log(obj[myVar]); // 👉️ Bobby Hadz
reactjs - Dynamically accessing object property in TypeScript - Stack Overflow
Object dynamic property acces in TypeScript - Stack Overflow
typescript - How to dynamically access to object properties? - Stack Overflow
typescript - How to type a function to dynamically access an object’s property? - Stack Overflow
Hi everyone, please help me with this compile error:
interface Person {
id: string,
name?: string,
age?: number
}
const originalPerson: Person = {id: "123", name: "Original"}
const updatePayload: Person = {id: "123", name: "Updated"};
Object.entries(updatePayload).forEach(([key, value]) => {
originalPerson[key as keyof Person] = value;
});The last line is having this error:
Looks like `value` is of type `any`, and `originalPerson[key as keyof Person]` is of type `never`. I also observed that if I change the type of `age` from `number` to `string` then the error will go away.
Not sure how can I fix this issue. For context: the original object is a very big object with multiple nested levels stored in a reactive store, while the updatePayload object is much much smaller so I may not want to reassign the original object to a new one every time I want to make an update.