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
Types in object destructuring
提问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 TFoo
property.
只会破坏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 name
and age
should be correctly inferred to string
and number
respectively.
该类型的属性name
和age
应正确推断string
和number
分别。
回答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 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
没有正确键入(any
或unknown
),也可以断言其类型:
const { foo } = bar as { foo: IFoo[] }; // foo type is IFoo[]