#Error 2322 with generic type over conditionnal type

9 messages · Page 1 of 1 (latest)

rain flax
#

I can't get a conditionnal type to work when used with a generic type

type TypeA = "a01" | "a02" | "a03" | "a04" | "a05" | "a06" | "a07" | "a08" | "a09" | "a10" | "a11";
type TypeB = "b01" | "b02" | "b03" | "b04" | "b05" | "b06";
type TypeC = "c01" | "c03" | "c04";

type Type = TypeA | TypeB | TypeC;

type Base<T extends Type = Type> = { type: T };
type Extended<T extends Type = Type> = T extends TypeB
  ? Base<T> & { extended: string }
  : Base<T> /*& { extended?: never; }*/;

const toExtended = <T extends TypeA>(base: Base<T>): Extended<T> => base; // error: Type 'Base<T>' is not assignable to type 'Extended<T>'.(2322)

Here's the playground

I don't see the logical error here, as T extends TypeA, Extended<T> should extended<TypeA> which in fact is Base<TypeA> and the return type should be correct.
What am I doing wrong?

foggy portalBOT
#

@rain flax Here's a shortened URL of your playground link! You can remove the full link from your message.

uaeruz#0

Preview:```ts
type TypeA =
| "a01"
| "a02"
| "a03"
| "a04"
| "a05"
| "a06"
| "a07"
| "a08"
| "a09"
| "a10"
| "a11"
type TypeB =
| "b01"
| "b02"
| "b03"
| "b04"
| "b05"
| "b06"
type TypeC = "c01" | "c03" | "c04"

type Type = TypeA | TypeB | TypeC

type Base<T extends Type = Type> = {type: T}
...```

void lintel
#

seems like it's to do with distribution

#

just type Extended<...> = T extends TypeB ? Base<T> : Base<T> gives the same error

#

though, even with fixing that, seems like it's still giving the same error in the original case

rain flax
#

It's a simplified case from a real one. Actually its more like :

type Extended<T extends Type = Type> = Base<T> & { common1: string; common2: string; common3: string; } & (T extends TypeB ? { extended1: string; extended2: string; } : { extended1?: never; extended2?: never; });
queen geode
#

Can you show your actual use case?

#

Generally, there is no way to implement conditional types safely. However you might be able to rewrite it into a mapped type, which can be implemented safely.

rain flax
#

@queen geode with my previous comment, it is my actual use case, anonymized