我正在尝试创建一个类,它允许传递回调来改变方法的副作用。如果不传递回调,则将直接调用该方法。这是一个基本示例:
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
- 为了避免重新声明对象的构造函数和属性的类型,您始终可以使用
构造函数赋值
的简写语法(只需添加private
或public
构造函数参数的关键字)
关于javascript - Typescript 可为 null 的回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59382054/