首页 > 解决方案 > typescript 的可区分联合可以与条件类型一起使用吗?

问题描述

假设我有以下 3 种类型:

type Apple = {
   type: "apple"
}

type Banana = {
  type: "banana"
}

type Fruit<T extends "apple" | "banana"> = T extends "apple" ? Apple : Banana

我有一个通用功能如下:

function fruit<T extends "apple" | "banana">(fr: Fruit<T>) {
    if (fr.type === "apple") {
        const element = fr
    }
}

为什么element仍然是 aFruit<T>而不是Apple?有没有办法使用条件类型获得有区别的联合工作?

标签: typescripttypescript-typingstypescript-genericstype-systems

解决方案


推荐阅读