Destructuring property of type `X | undefined` with a default

26 views Asked by At

I have

interface Foo {
  x: number;
  y: number;
}

interface Bar {
  foo: Foo | undefined;
}

declare const useBar: () => Bar;

const f = () => {
  const { foo } = useBar();

  // ...
}

I can use foo?.x to access properties and this works. But in practice foo has a lot more properties and I'd like to avoid ?. everywhere.

In JavaScript I can write

const { foo = {} } = useBar();

and then use foo.x and foo.y safely (in TypeScript terms, the type of foo is now Partial<Foo>). In TS this gives

Property 'x' does not exist on type '{}'

Reasonable, but is there a way to avoid this problem and get a Partial<Foo> anyway?

I see that

const { foo: { x, y } = {} } = useBar();

does work, but isn't ideal for my real use case; I'd have to rename them like

const { foo: { x: fooX, y: fooY } = {} } = useBar();
1

There are 1 answers

2
Alexey Romanov On

Rephrasing the question gave me an answer which works but I'm still hoping for something nicer:

const { foo = {} as Partial<Foo> } = useBar();

EDIT: improved version

where noFoo would be in the same module as useBar.