In plain JavaScript, we can read the value of an object's property using a variable.
That is, this is valid:
let obj = { a: 100, b: 'Need help with TypeScript', c: new Date() };
let prop = 'b';
console.log( obj[prop] ); // Need help with TypeScript
However, the below TypeScript annotation declaring prop as a string results in the indicated index error.
let obj: object = { a: 100, b: 'Need help with TypeScript', c: new Date() };
let prop: string = 'b';
console.log( obj[prop] ); // TypeScript error element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{}'.
How should I be annotating the above?
Edit Dec. 9, 2019: When I posted the question, I had assumed there would be a generic answer and not an answer explicitly dependent upon my example object.
My use case is a function, that accepts as an argument a property's name. The function sorts an array based on the name of the property passed. The original JavaScript code that I'm porting to TS will sort any array of objects.
objat all; let it be inferred as type{a: number, b: number, c: number}. As forprop, you also don't need to annotate it, but you should either changelettoconst, or uselet prop = "b" as const, like this.constmake a difference. I've not yet had a chance to try your suggestion for my specific case. I will though. (Please see my edits made today.)constmake a difference" The compiler treatsconstas signaling the intent that the value will not change (this is only true for primitives, but whatever), so it infers it as a narrower type. If you writelet prop = "b", it guesses that you wantpropto be astringbecause you might change it to some otherstringlater. If you writeconst prop = "b", it knows thatpropwill always be"b"so it infers the string literal type"b". I'd be happy to turn this into an answer if it meets your needs.