325

This

const { foo: IFoo[] } = bar;

and this

const { foo: Array<IFoo> } = bar;

will reasonably cause an error.

And this

const { foo: TFoo } = bar;

will just destructure TFoo property.

How can types be specified for destructured object properties?

3
  • Good question, but isn't it going to be able to infer the type from the definition of bar anyway?
    – user663031
    Sep 24, 2016 at 5:34
  • The @user663031 comment should be removed as it is misleading. Jun 16, 2020 at 12:04
  • @SasukeUchiha The article is unavailable, but most articles can be googled by article title. It was moved to mariusschulz.com/blog/… . It sheds some light indeed. Jun 16, 2020 at 12:10

7 Answers 7

451

It turns out it's possible to specify the type after : for the whole destructuring pattern:

const {foo}: {foo: IFoo[]} = bar;

Which in reality is not any better than plain old

const foo: IFoo[] = bar.foo;
3
  • 4
    But {foo} is not a value. It is what is usually called a "deconstructing assignment pattern". What you are seeing here is actually a special TypeScript feature which allows types of be associated with such patterns.
    – user663031
    Sep 24, 2016 at 7:02
  • 1
    Indeed, it's more like a special case, especially compared to let x, y, z: string which apparently specifies type for z only. I updated the answer.
    – artem
    Sep 24, 2016 at 7:19
  • 3
    The first one will be better if you need to do multiple destructuring. But the line would get so ugly that it might be better on separate lines.
    – jcollum
    Sep 1, 2021 at 20:59
100

If you don't mind using an interface when destructuring:

interface User {
  name: string;
  age: number;
}

const obj: any = { name: 'Johnny', age: 25 };
const { name, age }: User = obj;

The types of properties name and age should be correctly inferred to string and number respectively.

3
  • 40
    It's a rare case when you would like to use an interface for every destruction.
    – RA.
    Sep 13, 2019 at 3:14
  • @RA. What do you mean? Jul 13 at 13:12
  • @Mattwmaster58 I think he means "destructuring," and the idea is that destructured values may not always have a Type or Interface backing them.
    – slasky
    Aug 16 at 23:26
23

Next.js TypeScript example

I had scenarios like so:

const { _id } = req.query
if (_id.substr(2)) { 🚫
 ...
}

in which the req.query was typed like

type ParsedUrlQuery = { [key: string]: string | string[] }

so doing this worked:

const { _id } = req.query as { _id: string }
if (_id.substr(2)) { 🆗
 ...
}

The irony of this is Typescript was correct and I should have done:

const _id = String(req.query._id) ✅
2
  • how would the "correct way" work if you were destructuring multiple things?
    – Julix
    May 29 at 15:49
  • 1
    const { _id, abc, xyz } = req.query and I think those vars would be of type string | string[] | undefined but I didn't verify. May 29 at 16:48
13

A follow-up to my own question.

Types don't need to be specified for object properties, because they are inferred from the destructured object.

Considering that bar was typed properly, foo type will be inferred:

const bar = { foo: [fooValue], ... }; // bar type is { foo: IFoo[], ... }
...
const { foo } = bar; // foo type is IFoo[]

Even if bar wasn't correctly typed (any or unknown), its type can be asserted:

const { foo } = bar as { foo: IFoo[] }; // foo type is IFoo[]
3
  • 7
    This is true only when destructuring a typed object. If destructing something that came in as any then you need to type either that or the destructed variables. Aug 10, 2021 at 14:36
  • 1
    @SamuelNeff True, this is what the second snippet shows. The idea here is that it's beneficial to switch from untyped to typed code asap, in this case it's done before destructuring. Aug 10, 2021 at 16:44
  • Completely agree; the more everything is properly typed, the better TS will pick up type info automatically, and happier devs will be. Aug 11, 2021 at 14:08
6

If you want to destructor and rename:

const {foo: food}: {foo: IFoo[]} = bar;

It took me a second to get the above right.

1
0

It comes in handy when you're using multiple variables. If the function return is typed, the destructure is typed, without any need for defining a separate return type:

function getBananaDetail<detailType>(...args): { name: string, detail: detailType } {
//...
}
const { name, detail } = getBanana<number>()
0

The best way to assign types while destructuring:

const {foo} : {foo: IFoo[]} = bar;
1
  • Why is it the best way? Please respond by editing (changing) your answer, not here in comments (but *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** without *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** "Edit:", "Update:", or similar - the answer should appear as if it was written today). Nov 9 at 0:45

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.