I'm writing a function with refernece to callback functions. 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.
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)?
Typescript version: "
ˆ3.9.7
" (latest as to the day of this post)
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
{
"compilerOptions": {
"target": "es5",
// ....
},
}
Reason being interface Functon
has only been declared in lib.es6.d.ts
So depending on the needs, in order to solve this, you can
Either upgrade the target version in tsconfig.json
{ "compilerOptions": { "target": "es6" // was "es5" //... } }
Or specify the "lib"
to be included in compilation
{ "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],
});
}
}
);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.