Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Typescript callback parameter with specific type?

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

//'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) {}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading