繁体   English   中英

打字稿可为空回调

[英]Typescript nullable 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 构造函数的参数类型时,我必须复制它。 如何避免在私有属性和构造函数参数上声明类型?

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

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 T | null ,因为默认_click函数返回null
  • 为避免重新声明对象的构造函数和属性的类型,您始终可以使用简写语法进行constructor assignment (只需在构造函数参数中添加privatepublic关键字)
interface Callback<V> {
  (arg: () => void): V
}

class Button<T = void> {
  constructor(private callback?: Callback<T>) {}

  private onClick = () => {

  }

  public click = () => {
    if (this.callback) {
      return this.callback(this.onClick)
    } else {
      return this.onClick()
    }
  }
}

const button = new Button<number>(
  click => {
    click()
    return 2 +2 
  }
)

console.log(button.click()) // 4

我更新您的代码以解决您的问题

  • 为回调类型创建接口并添加private callback? 到构造函数以将参数注入类
  • 一个函数有很多类型,在打字稿中,一个不返回任何内容的void function是一个void function ,你返回的是 null,所以它与你的clickWrapper类型不匹配,我假设你不会从click函数返回任何东西所以我更新该类型以匹配void function

暂无
暂无

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

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