1

How can I use a property of an interface as a type for a variable in typescript ??
Here I want to access the property: string type and use it as a type for a variable but I cannot access it.

interface foo {
  bar?: {
    baz: {
      property: string;
    };
  };
}

function f(input: foo['bar']['baz']['property']) {
  console.log(input);
}

I was trying to find some optional chaining rule for this, but none of the JavaScript chaining methods worked here.

Error

Property 'baz' does not exist on type '{ baz: { property: string; } ' | undefined
Rocky
  • 117
  • 1
  • 1
  • 9

1 Answers1

4

To remove | undefined part from the foo['bar'] type you can use built-in NonNullable type, then you can access its properties:

function f(input: NonNullable<foo['bar']>['baz']['property']) {
  console.log(input);
}
artem
  • 46,476
  • 8
  • 74
  • 78