简体   繁体   English

对象解构中的类型

[英]Types in object destructuring

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.只会破坏TFoo属性。

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.属性nameage的类型应分别正确推断为stringnumber

NextJS Typescript example NextJS 打字稿示例

I had scenarios like so:我有这样的场景:

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

in which the req.query was typed like其中req.query的类型如下

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:具有讽刺意味的是,Typescript 是正确的,我应该这样做:

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:考虑到bar输入正确,将推断foo类型:

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:即使bar没有正确输入( anyunknown ),也可以断言它的类型:

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花了我一秒钟才把上面的东西弄好

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM