Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

129
Views
Mapping types in TypeScript

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 };

?

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

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};
about 4 years ago · Juan Pablo Isaza Report

0

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>;
about 4 years ago · Juan Pablo Isaza Report

0

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
}
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!