Hoffmann
Hoffmann

Reputation: 14719

How to select inner type that is part of a union

Selecting inner types (Type['fieldName']) in Typescript is very useful, with it you don't need to think of so many unique names for things. But I don't know how to select those inner types without giving them unique names when they are part of an union

Is it possible to figure out the values of those ? in the snippet below in order to get the type in the comment?

type A = {
  b:
    | {
        c: boolean;
      }
    | {
        d: number;
      }
    | null
    | undefined;
};

type Conly = A["b"][?] // { c: boolean }
type Donly = A["b"][?] // { d: number }
type CorD = A["b"][?]; // { c: boolean } | { d: number }

Upvotes: 0

Views: 133

Answers (3)

Karol Majewski
Karol Majewski

Reputation: 25790

The simplest solution is to find where A["b"] intersects with the target type.

type Conly = Extract<A["b"], { c: any }>
type Donly = Extract<A["b"], { d: any }>

CorD is a union of these two.

type CorD = Conly | Donly;

Note that you can also get Cord by removing null | undefined from A["b"].

type CorD = NonNullable<A["b"]>

Upvotes: 1

bela53
bela53

Reputation: 3485

You can use the built-in conditional helper types, namely Extract and NonNullable:

type Conly = Extract<A["b"], Record<"c", any>> // { c: boolean }
type Donly = Extract<A["b"], Record<"d", any>> // { d: number }
type CorD = NonNullable<A["b"]>; // { c: boolean } | { d: number }

Live code sample

Upvotes: 1

Nidin Vinayakan
Nidin Vinayakan

Reputation: 1227

TypeScript does not support Union to Tuple conversion. Instead, you can use Tuple then convert to Union.

type A = {
  b:[{ c: boolean } , { d: number}, null , undefined]
};

type B = A['b'][number]

type C = A['b'][0] // { c: boolean }
type D = A['b'][1] // { d: number }
type CorD = NonNullable<B> // { c: boolean } | { d: number }
// Another ways
type CorD_2 = Extract<B, C | D> // { c: boolean } | { d: number }
type CorD_3 = Exclude<B, null | undefined> // { c: boolean } | { d: number }

Upvotes: 0

Related Questions