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

TypeScript继承与子类型问题:如何检测重写方法参数逆变缺失?

TypeScript严格模式下检测方法重写的参数逆变缺失问题

问题背景

我开启了TypeScript所有严格模式选项,却写出了违反“继承意味着子类型”原则的非类型安全代码。以下代码未触发任何类型错误,但实际运行存在明显的类型安全隐患:

abstract class A {
    abstract do(x: number | string): number;
}

class B extends A {
    override do(x: number): number {
        return x;
    }
}

const a: A = new B();

const x: number = a.do("dupa");

console.log(x);

预期与实际结果

我原本期望TypeScript触发如下类型错误:

Error:(7, 14) TS2416: Property 'do' in type 'B' is not assignable to the same property in base type 'A'.
  Type '(x: number) => number' is not assignable to type '(x: string | number) => number'.
    Types of parameters 'x' and 'x' are incompatible.
      Type 'string | number' is not assignable to type 'number'.
        Type 'string' is not assignable to type 'number'.

但实际运行后控制台输出了"dupa",且更换不同类型对(包括不可赋值类型、null等,已开启strictNullChecks)后结果一致。这类赋值在通常情况下会触发类型错误,但此处未触发。经查证,这是TypeScript的特性而非Bug。

提问

是否存在解决方案,能让TypeScript类型检查器检测到重写方法参数类型的逆变缺失?


内容的提问来源于stack exchange,提问作者mskrzypczak

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 04:42:42