typescript - 键在应该用于索引类型时却不能使用

标签 typescript generics typescript-generics type-inference

我有以下 TS 代码

type Fruit = { kind: "apple" } | { kind: "grape"; color: "green" | "black" };
type FruitTaste<TFruit extends Fruit> = TFruit["kind"] extends "apple"
  ? "good"
  : TFruit["color"] extends "green"
  ? "good"
  : "bad";

Playground link

TFruit["color"] 出现错误

Type '"color"' cannot be used to index type 'TFruit'.

但不应该,因为我们处于三元方面,其中 TFruit 应该仅限于 { kind: "grape";颜色:“绿色” | “black”},并且 color 键应该存在。

奇怪的是,TS 的“运行时”版本不一定有任何问题:

type Fruit = { kind: "apple" } | { kind: "grape"; color: "green" | "black" };
const fruitTaste = (fruit: Fruit) =>
  fruit.kind === "apple" ? "good" : fruit.color === "green" ? "good" : "bad";

Playground link

这是为什么呢?如何实现 FruitTaste 类型?

最佳答案

我认为你可以通过分离类型 { kind: "apple"}{ kind: "grape"; 来实现它颜色:“绿色”| “黑色”}

type Apple = { kind: "apple" };
type Grape = { kind: "grape"; color: "green" | "black" };
type Fruit = Apple | Grape;
type FruitTaste<TFruit extends Fruit> = TFruit extends Grape
    ? TFruit["color"] extends "green"
        ? "good"
        : "bad"
    : "good";

关于typescript - 键在应该用于索引类型时却不能使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72928048/

相关文章:

typescript - 在 Typescript 中优雅地将两种类型组合成一个接口(interface)

c# - 是否可以创建仅接受具有特定属性的类型的泛型类

Java Generics - 抽象类抽象函数覆盖

typescript - 限制参数函数的返回类型

typescript - 根据类型保护推断函数的返回类型

java - 使用 Map 的方法 "getOrDefault()"

typescript 泛型 : infer type from the type of function arguments?

javascript - AgGrid 自定义时间过滤器

用于定义模型类型的 Typescript 接口(interface)

reactjs - 在 Typescript React 中使用 setInterval()