You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.15 04:27:21