skip to Main Content

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


  1. 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) {}
    
    Login or Signup to reply.
  2. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search