【发布时间】:2020-05-14 03:23:05
【问题描述】:
为什么当字符串是常量或简单字符串变量时,TypeScript 可以按字符串索引类型化对象,但如果从数组中拉出字符串,则无法通过字符串索引类型化对象
即考虑如下代码
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()
这两种方法都有效。
console.log(this['bar'])
//...
const index = 'bar';
console.log(this[index])
TypeScript 能够通过字符串索引我的对象。
然而,后面的例子中我在一个字符串数组上循环
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]])
}
不会运行/编译。我收到以下错误。
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])
所以这个错误消息——“字符串”类型的表达式不能用于索引“Foo”类型似乎与我的前两个例子背道而驰。
那么这里发生了什么?帮助一个糟糕的动态语言程序员理解 TypeScript 试图告诉我什么。一个样本的奖励积分实际上允许我迭代一个字符串数组并将一个字符串用作对象索引。
【问题讨论】:
标签: javascript typescript types ts-node