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?
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.
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) ✅
A follow-up to my own question.
Types don't need to be specified for object properties because they are inferred from 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[]
If you want to destructor and rename
const {foo: food}: {foo: IFoo[]} = bar;
Took me a second to get the above right
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.