我有以下 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";
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";
这是为什么呢?如何实现 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/