1

If I want to define a property in interface Two and have it be the same as a property in interface One. I can do it with this:

interface One {
  parent?: {
    child?: boolean;
  };
}

interface Two {
  parent?: One['parent']
}

But how can I copy a nested property? I would expect this to work:

interface Two {
  parent?: One['parent']['child']
}

but it errors:

Property 'child' does not exist on type '{ child?: boolean | undefined; } | undefined'.
1
  • The problem is that One['parent'] is optional, so its type is {child?: boolean | undefined} | undefined. Commented Aug 25, 2020 at 16:21

1 Answer 1

1

You can use Exclude to remove the undefined part from One['parent'], allowing you to access ['child']:

interface Two {
  parent?: Exclude<One['parent'], undefined>['child']
}

Playground link

Sign up to request clarification or add additional context in comments.

1 Comment

I'd only gotten as far as diagnosis (realizing the problem was the undefined) when you posted the solution. :-)

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.