【发布时间】:2019-11-06 11:46:40
【问题描述】:
我使用泛型和重载的组合来键入一个类,但是当启用strictNullChecks 时,我的重载中的可选参数出现问题。我怎样才能让它在启用strictNullChecks 的情况下工作?
一个简单的示例测试用例失败,并显示“'T | undefined' 类型的参数不可分配给 'undefined' 类型的参数。”仅当启用strictNullChecks 时:
class BaseClass { }
class BaseClass2 { }
class Test<T extends BaseClass, R extends BaseClass2> {
test(a: T): R;
test(a?: undefined): undefined;
test(a?: any) {
return a;
}
test2(b?: T) {
// Errors only when strictNullChecks is enabled (can be switched on in the options tab above)
return this.test(b)
}
}
const testClass = new Test<BaseClass, BaseClass2>()
// desired ouput
const output1: undefined = testClass.test2()
const output2: BaseClass2 = testClass.test2(new BaseClass())
编辑(2019 年 6 月 25 日 14:20):更新代码 sn-p 以反映所需的类型输出
【问题讨论】:
-
你应该可以使用条件类型来做到这一点:typescriptlang.org/docs/handbook/…。
标签: typescript typescript-typings