TypeScript默认参数绕过泛型类型校验问题及解决方法问询
如何阻止
new Example()赋值给Example<{ min: 1 }>类型? 首先定义以下类型与类:
type Config = { min?: number; max?: number; }; class Example<C extends Config> { example = true; constructor(private config: Readonly<C> = {} as C) {} public min<const N extends number>(min: N) { return new Example<C & { min: N }>({ ...this.config, min, }); } }
我需要创建类型为Example<{ min: 1 }>的实例,因此编写测试函数验证各种构造方式:
const test = (example: Example<{ min: 1 }>) => example;
预期可行的构造方式
以下写法均能正常运行:
test(new Example({ min: 1 })); test(new Example().min(1)); test(new Example({}).min(1));
预期不可行的构造方式
以下写法均按预期报错:
test(new Example({})); test(new Example({ min: 2 })); test(new Example().min(2));
不符合预期的情况
但执行下面的代码时,居然没有报错:
test(new Example());
默认参数{}显然不应该兼容{ min: 1 }类型。
虽然将test函数修改为泛型版本会触发报错,但这不是解决问题的核心:
const test = <C extends { min: 1 }>(example: Example<C>) => example; test(new Example());
真正的问题在于,下面这句代码应该抛出类型错误,但目前并没有:
const example: Example<{ min: 1 }> = new Example();
请问该如何实现让new Example()无法赋值给Example<{ min: 1 }>类型的目标?
内容的提问来源于stack exchange,提问作者Janek Eilts
相关产品推荐
相关产品推荐

