Here is the TS code I am working with:
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";
When trying to access TFruit["color"]
, it throws an error saying:
Type '"color"' cannot be used to index type 'TFruit'.
However, this should not be an issue as we are on a part where TFruit
is limited to only
{ kind: "grape"; color: "green" | "black" }
and the key color
should exist.
Interestingly, TypeScript does not have any problem with the "runtime" version of this code:
type Fruit = { kind: "apple" } | { kind: "grape"; color: "green" | "black" };
const fruitTaste = (fruit: Fruit) =>
fruit.kind === "apple" ? "good" : fruit.color === "green" ? "good" : "bad";
Why is this happening? How can I implement the FruitTaste
type correctly?