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

如何在判别式联合类型错误分支调用函数时触发TypeScript类型错误?

问题

我有一个由两个泛型类A<T1>和B<T2>组成的联合类型Union<T1, T2>,可通过类型守卫isA()和isB()进行类型收窄。需要定义函数onlyA(),满足以下要求:

  • 若类型未收窄(即仍为Union<T1, T2>),调用onlyA()不应产生TypeScript类型错误;若运行时实际为B实例,则抛出错误。
  • 若类型已收窄为B,调用onlyA()应触发TypeScript类型错误,明确该函数不可调用。

我曾尝试让B中的onlyA()返回never类型,虽能暗示返回值不存在,但无法产生明确的类型错误,并非理想方案。请问在TypeScript中是否有办法实现该行为?

原代码如下:

class A<T1>{
  val?: T1

  isA(): this is A<T1> {
    return true
  }

  isB(): this is B<never> {
    return false
  }

  onlyA(): T1 | undefined {
    return this.val
  }
}

class B<T2> {
  val?: T2

  isA(): this is A<never> {
    return false
  }

  isB(): this is B<T2> {
    return true
  }

  onlyA(): never {
    throw new Error("Can't access onlyA on B")
  }
}

type Union<T1, T2> = A<T1> | B<T2>

function returnUnion(): Union<string, string> {
  return new B()
}

let union = returnUnion()

union.onlyA()

if(union.isB()) {
  let test = union.onlyA()
  // 如何在这里触发类型错误?
}
解决方案

可以通过将B类中的onlyA定义为never类型的属性,并在构造函数中赋值一个抛出错误的函数,来实现需求:

  1. 类型层面:B类的onlyA为never类型,当类型收窄到B时,调用onlyA()会触发类型错误(提示“表达式不可调用,类型never没有调用签名”);而联合类型Union<T1, T2>中,onlyA的类型会被推断为A类中的函数类型,因此可以正常调用,不会报错。
  2. 运行时层面:B类的onlyA被赋值为一个抛出错误的函数,确保当未收窄类型但实际为B实例时,调用onlyA()会抛出错误。

修改后的代码如下:

class A<T1>{
  val?: T1

  isA(): this is A<T1> {
    return true
  }

  isB(): this is B<never> {
    return false
  }

  onlyA(): T1 | undefined {
    return this.val
  }
}

class B<T2> {
  val?: T2
  // 将onlyA声明为never类型
  onlyA: never;

  constructor() {
    // 赋值一个抛出错误的函数,并断言为never
    this.onlyA = (() => {
      throw new Error("Can't access onlyA on B");
    }) as never;
  }

  isA(): this is A<never> {
    return false
  }

  isB(): this is B<T2> {
    return true
  }
}

type Union<T1, T2> = A<T1> | B<T2>

function returnUnion(): Union<string, string> {
  return new B()
}

let union = returnUnion()

// 联合类型下调用,无类型错误
union.onlyA()

if(union.isB()) {
  // 此处会触发类型错误:表达式不可调用。类型 'never' 没有调用签名。
  let test = union.onlyA()
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.14 10:49:52