打字稿动态地从字符串调用方法

Typescript call a method from a string dynamically

我习惯在带有 @prismicio/client 的 vanilla JS 中使用这种类型的动态方法调用。但是使用 typeScript,我遇到了一个问题:

import Prismic from '@prismicio/client'

const options = {
    predicate: 'at',
    path: 'document.type',
    value: 'page'

}

Prismic.Predicates[options.predicate](options.path, options.value);

不幸的是解析器告诉我这个:

{
    "resource": "/Users/a143ji/Projects/ai-marketplace-backend/src/prismic.ts",
    "owner": "typescript",
    "code": "7053",
    "severity": 8,
    "message": "Element implicitly has an 'any' type because expression of type 'any' can't be used to index type '{ at(fragment: string, value: string | number | boolean | Date | (string | number | boolean | Date)[]): string; not(fragment: string, value: string | number | boolean | Date | (string | ... 2 more ... | Date)[]): string; ... 28 more ...; geopoint: { ...; }; }'.",
    "source": "ts",
    "startLineNumber": 11,
    "startColumn": 16,
    "endLineNumber": 11,
    "endColumn": 45
}

这是因为options是可变对象,TS不确定options.predicate是否可以用作索引。

要修复它,您应该为您的对象添加 as const 前缀:

import Prismic from '@prismicio/client'

const options = {
    predicate: 'at',
    path: 'document.type',
    value: 'page'

} as const

Prismic.Predicates[options.predicate](options.path, options.value); // ok

Playground