Home > Mobile >  How to dereference optional field in typescript?
How to dereference optional field in typescript?

Time:09-14

I need to dereference an optional field from an interface like below

interface Sample {
  key1?: Array<Obj1>
}

interface Obj1 {
  a?: Obj2;
}

interface Obj2 {
  b?: string;
}

const a: Sample["key1"][number]["a"]["b"] = "asd";

However it gives me an error at Sample["key1"][number] saying Type 'Obj1[] | undefined' has no matching index signature for type 'number'.

How to achieve this?

CodePudding user response:

You have to take out null and undefined at each step of indexing with NonNullable:

const a: NonNullable<NonNullable<Sample["key1"]>[number]["a"]>["b"] = "asd";

Playground Link

CodePudding user response:

Sample["key1"] might Obj1[]or undefined. Try

Sample["key1"]?[number]
  • Related