Reputation: 207
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.
Upvotes: 2
Views: 3068
Reputation: 372
// 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");
});
Upvotes: 1
Reputation: 16147
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');
});
Upvotes: 2
Reputation: 912
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;
}
Upvotes: 1