Typescript access nested conditional type

Viewed 150

I am trying to access the nested type b given the following type definition and that a is not null:

type Abc = {
  a: {
    b: number
  } | null
}

However, the following code causes an error: Property 'b' does not exist on type '{ b: number; } | null'.ts(2339)

const test: Abc["a"]["b"] = 3;
1 Answers

You could change it to:

const test: NonNullable<Abc["a"]>["b"] = 3;

That's a bit of a mouthful though. You could also consider splitting it into a couple interfaces, and referring to the inner one directly:

interface Thing {
  b: number
}

type Abc = {
  a: Thing | null
}

const test: Thing["b"] = 3;
Related