[英]How can I run a function into an Object by your key name in TypeScript?
我有一个像这样的 Object:
const Foo = {
bar: (): void => { console.log('foo.bar') },
baz: (): void => { console.log('foo.baz') },
};
我想这样调用这些函数:
Foo["bar"]();
Foo["baz"]();
不幸的是,TypeScript 不能编译这段代码。
Element implicitly has an 'any' type because expression of type 'string' can't be used to index type {MY_OBJECT}
我需要做什么才能通过索引名称启用 function 调用?
#编辑
我创建了这个片段来显示问题:
您提供的代码至少在 typescript 3.9.2
中按原样工作。 尽管有可能 1. 它在早期版本的 TS 中不能以这种方式工作,或者 2. 您提供的代码只是一个示例,并不完全是您遇到问题的代码。
在任何一种情况下,错误都与string
和string
的子类型( bar
和baz
)有关。
您的 object Foo
的类型被推断为:
{ [key in 'bar' | 'baz']: () => void }
与
{ [key in string]: () => void }
或者换句话说,键只能是string
的特定子类型。
当你运行Foo["bar"]();
,最新的 typescript 应正确解释提供为'bar'
的索引,但早期版本可能不会这样做。
您可以通过强制 TS 使用const 断言将其解释为文字类型来解决此问题,如下所示:
const key1 = 'bar' as const
Foo[key1]() // should not error
const key2 = 'baz' as const
Foo[key2]() // should not error
或者,您可以使用更广泛的类型为您的Foo
object 提供类型注释,如下所示:
const Foo: {[key in string]: () => void} = {
bar: (): void => { console.log('foo.bar') },
baz: (): void => { console.log('foo.baz') },
};
Foo['bar']() // should not error
Foo['baz']() // should not error
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.