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

1 Answer 1

5

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);
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.