When working with plain JavaScript, we have the ability to access an object's property value using a variable.
For example, this is permitted:
let obj = { a: 100, b: 'Need help with TypeScript', c: new Date() };
let prop = 'b';
console.log( obj[prop] ); // Need help with TypeScript
However, when introducing TypeScript and declaring prop
as a string, it may lead to an index error as shown below.
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 '{}'.
What would be the correct way to annotate the code above?
Edit Dec. 9, 2019: When initially posting the question, I assumed there would be a general solution that isn't solely reliant on my specific object example.
In my scenario, I have a function that takes a property name as an argument. This function is responsible for sorting an array based on the provided property name. The original JavaScript code I'm migrating to TypeScript is capable of sorting any array of objects.