Why can TypeScript index a typed object by string when that string is a constant or a simple string variable, but it's unable to index a typed object by a string if that string is pulled out of an array
That is, consider the following code
class Foo {
public bar: string = 'hello';
public test() {
// this works
console.log(this['bar'])
// this also works
const index = 'bar';
console.log(this[index])
// in both cases above I have successfully used
// a string as an index for my type Foo
// However, this doesn't work
const props:string[] = ['bar']
for(const [key,value] of props.entries()) {
console.log(value); // prints 'bar' to terminal/console
console.log(this[value])
}
// Nor does this
for(let i=0;i<props.length;i++) {
console.log(this[props[i]])
}
// when looping over an array of string and trying to use the
// string to index the object, I get the following error
// why.ts:20:25 - error TS7053: Element implicitly has an 'any'
// type because expression of type 'string' can't be used to
// index type 'Foo'.
}
}
const foo = new Foo;
foo.test()
class Foo {
public bar: string = 'hello';
public test() {
// this works
console.log(this['bar'])
// this also works
const index = 'bar';
console.log(this[index])
// in both cases above I have successfully used
// a string as an index for my type Foo
// However, this doesn't work
const props:string[] = ['bar']
for(const [key,value] of props.entries()) {
console.log(value); // prints 'bar' to terminal/console
console.log(this[value])
}
// Nor does this
for(let i=0;i<props.length;i++) {
console.log(this[props[i]])
}
// when looping over an array of string and trying to use the
// string to index the object, I get the following error
// why.ts:20:25 - error TS7053: Element implicitly has an 'any'
// type because expression of type 'string' can't be used to
// index type 'Foo'.
}
}
const foo = new Foo;
foo.test()
Both of these work.
console.log(this['bar'])
//...
const index = 'bar';
console.log(this[index])
TypeScript's able to index my object by a string.
However, the later examples where I'm looping over a string array
const props:string[] = ['bar']
for(const [key,value] of props.entries()) {
console.log(value); // prints 'bar' to terminal/console
console.log(this[value])
}
for(let i=0;i<props.length;i++) {
console.log(this[props[i]])
}
won't run/compile. I get the following error.
why.ts:42:17 - error TS7053: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'Foo'.
No index signature with a parameter of type 'string' was found on type 'Foo'.
42 console.log(foo[value])
So this error message -- expression of type 'string' can't be used to index type 'Foo' seems to run counter to my first two examples.
So what's going on here? Help a poor dynamic language programmer understand what TypeScript is trying to tell me. Bonus points for a sample that actually allows me to iterate over an array of strings and use one as an object index.