Dynamic
Dynamic

Reputation: 507

Typescript access nested conditional type

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;

Upvotes: 2

Views: 167

Answers (1)

Nicholas Tower
Nicholas Tower

Reputation: 84922

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;

Upvotes: 3

Related Questions