I am new to TypeScript and I am trying to understand how to define the callback for a function of which the callback must have a parameter type but i don’t know the correct syntax for it.
This is my current function:
function LoadJSON(callback: Function(string)) {
FS.readFile(dir + '/' + file, (err, fd) => {
if (err) {
console.log(err);
return;
}
console.log(fd);
console.log('File loaded');
callback(JSON.stringify(fd));
return;
});
}
The issue is this line:
//'string' only refers to a type, but is being used as a value here.ts(2693)
function LoadJSON(callback: Function(string))
What is the correct syntax ?
I am trying to make it clear the provided callback function must take a string.
>Solution :
The syntax that you are using is invalid in the typescript. What you are looking for has the following pattern:
type Func = (argName: argType) => ReturnType
I presume you don’t have any return type so you can replace ReturnType with void which represents that function is not returning anything.
function LoadJSON(callback: (argName: string) => void) {}