简体   繁体   English

如何通过您在 TypeScript 中的键名将 function 运行到 Object 中?

[英]How can I run a function into an Object by your key name in TypeScript?

I have an Object like this:我有一个像这样的 Object:

const Foo = {
    bar: (): void => { console.log('foo.bar') },
    baz: (): void => { console.log('foo.baz') },
};

I would like to call these functions this way:我想这样调用这些函数:

Foo["bar"]();
Foo["baz"]();

Unfortunately, TypeScript doesn't compile this code.不幸的是,TypeScript 不能编译这段代码。

Element implicitly has an 'any' type because expression of type 'string' can't be used to index type {MY_OBJECT}

What do I need to do to enable the function call by the index name?我需要做什么才能通过索引名称启用 function 调用?

#EDIT #编辑

I create this snippet to show the problem:我创建了这个片段来显示问题:

Playground Link 游乐场链接

The code you provided works as-is, at least in typescript 3.9.2 .您提供的代码至少在 typescript 3.9.2中按原样工作。 It's possible though that either 1. it does not work that way in an earlier version of TS, or 2. the code you provided was simply an example and isn't exactly the code you have trouble with.尽管有可能 1. 它在早期版本的 TS 中不能以这种方式工作,或者 2. 您提供的代码只是一个示例,并不完全是您遇到问题的代码。

In either case, the error has to do with string and subtypes of string ( bar and baz ).在任何一种情况下,错误都与stringstring的子类型( barbaz )有关。

Your object Foo 's type is inferred as:您的 object Foo的类型被推断为:

{ [key in 'bar' | 'baz']: () => void }

as opposed to

{ [key in string]: () => void }

or in other words, the keys can only be specific sub-types of string .或者换句话说,键只能是string的特定子类型。

When you run Foo["bar"]();当你运行Foo["bar"](); , the latest typescript should correctly interpret the index provided as 'bar' , but an earlier version might not be doing so. ,最新的 typescript 应正确解释提供为'bar'的索引,但早期版本可能不会这样做。

You can get around this by forcing TS to interpret this as a literal type using a const assertion like so:您可以通过强制 TS 使用const 断言将其解释为文字类型来解决此问题,如下所示:

const key1 = 'bar' as const
Foo[key1]() // should not error

const key2 = 'baz' as const
Foo[key2]() // should not error

Alternatively, you can provide a type annotation to your Foo object with a wider type like so:或者,您可以使用更广泛的类型为您的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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM