typescript 对象解构中的类型

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39672807/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 07:20:55  来源:igfitidea点击:

Types in object destructuring

typescriptdestructuring

提问by Estus Flask

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 TFooproperty.

只会破坏TFoo财产。

How can types be specified for destructured object properties?

如何为解构的对象属性指定类型?

回答by artem

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;

回答by Stephen Paul

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 nameand ageshould be correctly inferred to stringand numberrespectively.

该类型的属性nameage应正确推断stringnumber分别。

回答by Estus Flask

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 barwas typed properly, footype will be inferred:

考虑到bar输入正确,foo类型将被推断:

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

Even if barwasn't correctly typed (anyor unknown), its type can be asserted:

即使bar没有正确键入(anyunknown),也可以断言其类型:

const { foo } = bar as { foo: IFoo[] }; // foo type is IFoo[]