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.
2
Answers
The syntax that you are using is invalid in the typescript. What you are looking for has the following pattern:
I presume you don’t have any return type so you can replace
ReturnType
withvoid
which represents that function is not returning anything.I don’t have enough rep to comment and just wanted to extend user wonderflame’s
callback: (str: string) => void
answer with the TypeScript Functions Docs. The docs are very helpful, informative, and will help you understand functions in TypeScript further and give you a further understanding of why the answer is correct.The site gives the example:
The syntax
(a: string) => void
means “a function with one parameter, named a, of type string, that doesn’t have a return value”. Just like with function declarations, if a parameter type isn’t specified, it’s implicitly any.