Reputation: 1025
What is the proper way to reference an object property using bracket notation in TypeScript?
In regular JavaScript, I can do this:
returnValue(object, key) {
return object[key];
}
And if I call returnValue({someKey: 1}, "someKey")
, the function returns 1
.
When I try to do this in TypeScript, I receive:
TS1003: Identifier expected. Name expected.
What's the proper way to do this?
Upvotes: 1
Views: 4635
Reputation: 4412
You might consider using keyof
:
interface YourObj {
someKey: string;
someOtherKey: number;
}
function returnValue(obj: YourObj, key: keyof YourObj) {
return obj[key];
}
console.log("Object value = " + returnValue({someKey: "someValue", someOtherKey: 1}, "someKey"))
This will give you compilation errors if you call returnValue
on anything that isn't YourObj
and any key that doesn't appear in YourObj
Upvotes: 1
Reputation: 24134
Typescript is a strict superset of JavaScript, so JavaScript is legal in Typescript.
JavaScript object property accessors using the dot notation or the bracket notation are both valid in Typescript. Running the example code below does not generate any errors or warnings.
For more assistance, you will need to provide a minimal, reproducible example.
See TypeScript Playground Demo
function returnValue(obj: any, key: string) {
return obj[key];
}
console.log("Object value = " + returnValue({someKey: 1}, "someKey"))
Object value = 1
Upvotes: 0