¿Es posible en TS transformar este tipo
type input = { a: 1; b: 2; c: 3; };en este tipo
type output = { a: 1 } | { b: 2 } | { c: 3 };?
Puedes hacerlo:
type input = { a: 1; b: 2; c: 3; }; type output = { a: 1 } | { b: 2 } | { c: 3 }; let i : input = { a: 1, b: 2, c: 3 }; let o : output; let {a, b, c} = i; o = {a} || {b} || {c};Honestamente, no tengo idea de cómo implementar esto desde cero. Pero aquí hay una biblioteca que hace exactamente esto y mucho más (ts-toolbelt):
import { Object } from 'ts-toolbelt'; type Input = { a: 1; b: 2; c: 3; }; type Output = Object.Either<Input, keyof Input>;No estoy seguro de si esto se escala a tipos de input más complicados, puede volverse extraño con cosas anidadas
type input = { a: 1; b: 2; c: 3; }; // given key K, construct {[K]: T[K]} type m2<T, K extends keyof T> = {[k in K]: T[k]} // for each key K in T, construct {[K]: T[K]}, and union the results type m1<T, K extends keyof T> = K extends any ? m2<T, K> : never; type map<T> = m1<T, keyof T>; type result = map<input> declare const result : result; if ("a" in result) { result.a // type 1 } else if ("b" in result) { result.b; // type 2 } else { result.c // type 3 }