flatterino
flatterino

Reputation: 1025

Typescript Error TS1003 when attempting to access object properties using bracket notation

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

Answers (2)

xandermonkey
xandermonkey

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

Christopher Peisert
Christopher Peisert

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"))

Output

Object value = 1

Upvotes: 0

Related Questions