我正在编写一个引用回调函数的函数。但是我似乎无法访问它的属性。
const example = (
callback: (...args: unknown[]) => unknown
): void => ({
name: callback.name // <- errors
// ...
})
我的问题是,typescript不喜欢我访问函数属性。
name: callback.name
// ts(2339): Property 'name' does not exist on type '(...args: any[]) => any'
访问函数名称(或其他 Function
属性)的正确方法是什么?
Typescript version: "
ˆ3.9.7
" (latest as to the day of this post)
最佳答案
好吧,我找到了导致它的原因以及解决方法。
出现这个问题是因为我的 tsconfig.json
在我的项目中是如何设置的。
// tsconfig.json
{
"compilerOptions": {
"target": "es5",
// ....
},
}
原因是 interface Functon
仅在 lib.es6.d.ts
中声明
所以根据需要,为了解决这个问题,可以
要么升级
tsconfig.json
中的目标版本{ "compilerOptions": { "target": "es6" // was "es5" // ... } }
或者指定要包含在编译中的
"lib"
{ "compilerOptions": { "target": "es5", "lib": ["es6", "dom", "es2016", "es2017", "es5"], // needs at least es6 // ... } }
关于javascript - 为什么我无法访问函数属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63214752/