javascript - Typescript 可为 null 的回调

标签 javascript typescript callback

我正在尝试创建一个类,它允许传递回调来改变方法的副作用。如果不传递回调,则将直接调用该方法。这是一个基本示例:

class Button<T = void> {
    private clickWrapper?: (click: Function) => T

    private _click() {
        // do the click here
        return null;
    }

    constructor(clickWrapper?: (click: Function) => T) {
        this.clickWrapper = clickWrapper;
    }

    public click() {
        if (this.clickWrapper) {
            return this.clickWrapper(this._click.bind(this));
        } else {
            return this._click();
        }
    }

}


class Foo {

    public doStuff() {
        console.log('hello');
    }

}



const button = new Button<Foo>(click => {
    // do some stuff
    click();
    return new Foo();
});

const foo = button.click();
foo.doStuff();


const button2 = new Button();
button2.click();

这可行,但是 foo.doStuff() 提示 foo 可能为 null - 即使在这种情况下我提供了一个 clickWrapper,所以 button.click()< 的返回值 不能为 null,它必须是 Foo 的实例。有更好的方法来定义它吗?

第二个问题是,当我已经为 Button.clickWrapper 声明了 Button 构造函数的参数类型时,我必须复制它。如何避免在私有(private)属性和构造函数参数上声明类型?

最佳答案

我已经更新了您的代码片段:

class Button<T = null> {
  constructor(private clickWrapper?: (click: Function) => T) {}

  private _click() {
    // do the click here
    return null;
  }

  public click(): T {
    if (this.clickWrapper) {
      return this.clickWrapper(this._click.bind(this));
    } else {
      return this._click();
    }
  }
}

class Foo {
  public doStuff() {
    console.log("hello");
  }
}

const button = new Button<Foo>(click => {
  // do some stuff
  click();
  return new Foo();
});

const foo = button.click();
foo.doStuff();

const button2 = new Button();
button2.click();

有两件事:

  • TypeScript 无法确定您的 public click 函数的确切返回类型,因此它假定 T | null,因为默认的 _click 函数返回 null
  • 为了避免重新声明对象的构造函数和属性的类型,您始终可以使用构造函数赋值的简写语法(只需添加 privatepublic 构造函数参数的关键字)

关于javascript - Typescript 可为 null 的回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59382054/

相关文章:

javascript - Node.js,为事件 'data' 分配回调函数

javascript - 如何在移动 iO 上启用平滑滚动?

javascript - 检查 Typescript 类是否已实例化

javascript - 简化 promise

javascript - 从 DOM 复制字符串

angular - 如何修复我的 Angular 测验应用程序中多选题的评分问题?

android - 将回调从 Activity 发送到 Fragment

c++ - 无法将模板函数作为回调参数传递

javascript - 单元测试 - 通量和数据持久性

javascript - jQuery 扩展多个对象具有相同的功能