2

I want to implement an interface with a list of functions and attributes, few functions required to work on callback mode. For example

interface Writer{
     readData : (fileLocation: string) => void;
     generatData: (fileLocation: string) => void;
}

I would like to execute generateData function and notify after job is done. For example

const WriterInstance:Writer ={
   generateData("C:/workspace" , ()=>{
       console.log("work is done");
   });
   readData("C:/workspace/file1.text" , ()=>{
       console.log("work is done");
   })
}

I am totally misunderstanding the syntax & invocation of callbacks in the interface. If anyone explains with example then it will be great.

3 Answers 3

2

Just imagine that the callback function is a normal parameter. Then, define WriterInstance as a normal object - Just define it's properties

interface Writer{
  readData : (fileLocation: string, callback: () => void) => void;
  generateData: (fileLocation: string, callback: (error: Error, data?: any) => void) => void;
}

const WriterInstance: Writer = {
  readData: (fileLocation: string, callback: () => void) => {
    // dome something with fileLocation
    callback();
  },

  generateData: (fileLocation: string, callback: (error: Error, data?: any) => void) => {
    // dome something with fileLocation
    callback(null, true);
  }
}

// usage of WriterInstance
WriterInstance.generateData('C:/workspace/file1.text', (error, data) => {
  if (error) {
    console.log('work is not done');
    return console.log(error);
  }
  console.log('work is done');
});
Sign up to request clarification or add additional context in comments.

Comments

1
// Define writer interface
interface Writer{
     readData : (fileLocation: string, callback: () => void) => void;
     generateData: (fileLocation: string, callback: () => void) => void;
}

// Create writer
const writerInstance: Writer = {
   generateData: (fileLocation: string, callback: () => void) => {
    // generate data
    callback();
},
   readData: (fileLocation: string, callback: () => void) => {
    //read data
    callback();
}
}

// Call writer methods
writerInstance.generateData("C:/workspace", ()=>{
     console.log("work is done");
 });

writerInstance.readData("C:/workspace/file1.text" , ()=>{
     console.log("work is done");
 });

Comments

1

In your interface, you want to represent a function with two parameters, the first one is a string and the second one is a function so you can write it like that:

interface Writer{
     readData : (fileLocation: string, callback: ()=>void) => void;
     generateData: (fileLocation: string, callback: ()=>void) => void;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.