简体   繁体   English

在接口 Typescript 中定义回调

[英]Define Callback in interface Typescript

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.我想执行 generateData function 并在工作完成后通知。 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.如果有人举例说明,那就太好了。

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:在你的界面中,你想用两个参数表示一个 function,第一个是字符串,第二个是 function,所以你可以这样写:

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

Just imagine that the callback function is a normal parameter.试想一下,回调 function 是一个普通参数。 Then, define WriterInstance as a normal object - Just define it's properties然后,将WriterInstance定义为普通的 object - 只需定义它的属性

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');
});
// 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");
 });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM