I came across this issue in TypeScript types. I'm using a conditional type based on a different property in the same interface to determine the type of one property. Here, the property slicer in FruitBasket is either AppleSlicer or BananaSlicer depending on the type.
If you look at the function test, it receives a instance of FruitBasket, which can be either Apple or Banana. So, I narrow down the type by checking that the type is equal to one of them, but it still complains that basket.slicer is not deterministic. But, it should have all information it needs to determine that it's an AppleSlicer.How can I fix this?
I'm using TypeScript 4.5.4.
enum Fruits {
Apple = "Apple",
Banana = "Banana",
}
// These interfaces can have completely different shapes as shown.
interface AppleSlicer { apple(): void }
interface BananaSlicer { banana(): void }
export type FruitSlicer<TType> = TType extends typeof Fruits.Apple
? AppleSlicer
: TType extends typeof Fruits.Banana
? BananaSlicer
: never
export interface FruitBasket<TType extends Fruits> {
type: TType
slicer: FruitSlicer<TType>
}
const test = (basket: FruitBasket<Fruits>) => {
if (basket.type === Fruits.Apple) {
// This gives me a compile error because basket.slicer is either AppleSlicer or BananaSlicer.
// But, it should have all information it needs to deduce that it can only be an AppleSlicer
basket.slicer.apple()
}
}