Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript interface type values to union type

Tags:

typescript

Is it possible to get a union type with all type values from an interface in typescript?

For example, when an interface is given as

interface A {
  a: string;
  b: () => void;
  c: number;
  d: string;
  e: 'something';
}

the result should be

type B = string | () => void | number | 'something';

I have no clue, how I would approach this problem, if it is even possible.

like image 273
Peter Lehnhardt Avatar asked Apr 25 '19 14:04

Peter Lehnhardt


1 Answers

You can use keyof e.g.

 type B = A[keyof A] // will be string | number | (() => void)

The type something will not appear since the compiler does not differentiate between the type string and something - since both are strings it will omit it in the type B.

like image 136
Murat Karagöz Avatar answered Sep 29 '22 10:09

Murat Karagöz