Type properties to discriminated union types

I'd like to transform a type to a discriminated union type:

type Current = {
  A : number,
  B : string,
}

to

type Target= {
  type: 'A',
  value: number
}
| {
  type: 'B',
  value: string
}

So that I can discriminate the result.

function handle(result: ToTarget<Current>) {
 switch(result.type){
  case 'A':
   return result.value // number
  case 'B':
   return result.value // string
 } 
}

The closest I got was:

type ToTargetA<U> = { code: keyof U, value : U[keyof U] } 
// code and value are not in sync so code is 'A | B' and value is 'number | string' but discriminating on code does not narrow value.

type ToTargetB<U, K extends keyof U = any> = { code: keyof K, value : U[K] }
// requires me to specify K as a generic parameter which is not what I want.

I tried several conditional type expressions but couldn't get much closer.



Read more here: https://stackoverflow.com/questions/64398068/type-properties-to-discriminated-union-types

Content Attribution

This content was originally published by nathanwinder at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: