Types in object destructuring Types in object destructuring typescript typescript

Types in object destructuring


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;


I'm clearly a bit late to the party, but:

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.


NextJS Typescript example

I had scenarios like so:

const { _id } = req.queryif (_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 = (req.query._id || '').toString() ✅ 

or make some helper method like this:

const qs = (  (q: ParsedUrlQuery) => (k: string) => (q[k] || '').toString())(req.query) 💪

that I could reuse like this:

const _id = qs('_id') 👍