Content pfp
Content
@
0 reply
0 recast
2 reactions

Darryl Yeo 🛠️ pfp
Darryl Yeo 🛠️
@darrylyeo
Any TypeScript gurus in the house who can help me troubleshoot this? What am I fundamentally misunderstanding about type parameters / conditionals here?
8 replies
1 recast
11 reactions

Darryl Yeo 🛠️ pfp
Darryl Yeo 🛠️
@darrylyeo
```ts enum Type { A = 'A', B = 'B', } type FromThing<T extends Type = Type> = ( & { type: Type, } & ( T extends Type.A ? { A: number } : T extends Type.B ? { B: string } : Record<string, never> ) ) type ToThing<T extends Type = Type> = ( & { type: Type, } & ( T extends Type.A ? { a: number } : T extends Type.B ? { b: string } : Record<string, never> ) ) const transform = < T extends Type = Type >( fromThing: FromThing<T> ): ( ToThing<T> ) => ({ type: fromThing.type, ...( fromThing.type === Type.A && 'A' in fromThing && fromThing.A && { a: fromThing.A, } ), ...( fromThing.type === Type.B && 'B' in fromThing && fromThing.B && { b: fromThing.B, } ), }) ```
3 replies
0 recast
1 reaction

Darryl Yeo 🛠️ pfp
Darryl Yeo 🛠️
@darrylyeo
Most importantly, is this function signature possible to satisfy *without* type assertions (`as`) or type predicates (`is`)?
1 reply
0 recast
0 reaction

Monteluna pfp
Monteluna
@monteluna
These are called Generalized Algebraic Data Types in type theory land. Anytime you're doing type contraints as a function, it's a GADT. Basically any other logic that maps a type parameter to a specific type output that is higher than sum or product types *needs* a GADT. Don't really have a ton of time to stare at this problem, but this article might spin some wheels. https://www.matteopellegrino.dev/posts/ts-gadt
0 reply
1 recast
1 reaction