Peter Lehnhardt
Peter Lehnhardt

Reputation: 4995

Typescript interface type values to union type

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.

Upvotes: 18

Views: 7175

Answers (2)

Sohan
Sohan

Reputation: 6809

You need something that is advance typescript.

Below example keyof A is completely interchangeable with string | () => void | number | 'something';. The difference is that if you add another property to A, say myfunc: string, then keyof A will automatically update to be string | () => void | number | something |myfunc. And you can use keyof in generic contexts like pluck, where you can’t possibly know the property names ahead of time. That means the compiler will check that you pass the right set of property names to pluck:

pluck(A, ['number ', 'unknown']); // error, 'unknown' is not in string | () => void | number | 'something';

It can be

let B :keyof A;

Upvotes: 1

Murat Karagöz
Murat Karagöz

Reputation: 37614

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.

Upvotes: 34

Related Questions