[英]Why am I unable to access function properties?
I'm writing a function with refernece to callback functions.我正在写一个 function 参考回调函数。 However I cannot seem to access its properties.
但是我似乎无法访问它的属性。
const example = (
callback: (...args: unknown[]) => unknown
): void => ({
name: callback.name // <- errors
// ...
})
My issue is, typescript doesn't like me accessing the funciton properties.我的问题是, typescript不喜欢我访问功能属性。
name: callback.name
// ts(2339): Property 'name' does not exist on type '(...args: any[]) => any'
What would be the correct way of accessing the function name (or other Function
properties for that matter)?访问 function 名称(或其他
Function
属性)的正确方法是什么?
Typescript version: "
ˆ3.9.7
" (latest as to the day of this post)Typescript 版本:“^
ˆ3.9.7
” (截至发帖当天最新)
Allright I found what caused it and how to fix it.好吧,我找到了导致它的原因以及如何解决它。 This issue occured because of how my
tsconfig.json
was set up inside my project.发生此问题的原因是我的
tsconfig.json
是如何在我的项目中设置的。
// tsconfig.json
{
"compilerOptions": {
"target": "es5",
// ....
},
}
Reason being interface Functon
has only been declared in lib.es6.d.ts
interface Functon
函数的原因仅在lib.es6.d.ts
中声明
So depending on the needs, in order to solve this, you can所以根据需要,为了解决这个问题,你可以
Either upgrade the target version in tsconfig.json
在
tsconfig.json
中升级目标版本
{ "compilerOptions": { "target": "es6" // was "es5" //... } }
Or specify the "lib"
to be included in compilation或者指定要包含在编译中的
"lib"
{ "compilerOptions": { "target": "es5", "lib": ["es6", "dom", "es2016", "es2017", "es5"], // needs at least es6 //... } }
import { Dispatch, SetStateAction } from 'react'
import { FieldType, ErrorType } from 'types/FieldTypes'
const handleErrors = (
setField: Dispatch<SetStateAction<FieldType>>,
callback: {
name: 'name of callback',
run: (args) => {
try {
callback.run();
} catch (e) {
const newError: ErrorType = {
name: callback.name,
message: e.message,
};
setField((prevData) => ({
...prevData,
errors: [...prevData.errors || [], newError],
});
}
}
);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.