Evanss
Evanss

Reputation: 23583

Define nested value from one interface in another interface in TypeScript?

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'.

Upvotes: 1

Views: 133

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370729

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

Upvotes: 1

Related Questions