Is it possible in TS to transform this type
type input = {
a: 1;
b: 2;
c: 3;
};
into this type
type output = { a: 1 } | { b: 2 } | { c: 3 };
?
You can do this:
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};
Honestly, I have no idea how to implement this from scratch. But here's a library that does exactly this and much more (ts-toolbelt):
import { Object } from 'ts-toolbelt';
type Input = {
a: 1;
b: 2;
c: 3;
};
type Output = Object.Either<Input, keyof Input>;
Not sure if this scales to more complicated input types, might get weird with nested things
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
}