使用TypeScript中的类型进行对象分解

I was using TypeScript in Deno to build a sample project and I had to destructure an object. I am familiar with TypeScript basics but sometimes I hit a problem.

我在Deno中使用TypeScript来构建示例项目,并且必须解构对象。 我熟悉TypeScript基础知识,但有时会遇到问题。

Object destructuring was one of those.

对象解构就是其中之一。

I wanted to do

我想做

const { name, age } = body.value

I tried adding the string and number types like this:

我尝试添加像这样的stringnumber类型:

const { name: string, age: number } = body.value

But this didn’t work. It apparently worked, but in reality this is assigning the name property to the string variable, and the age property value to the number variable.

但这没有用。 它显然起作用了,但是实际上这是将name属性分配给string变量,并将age属性值分配给number变量。

The correct syntax is this:

正确的语法是这样的:

const { name, age }: { name: string; age: number } = body.value

The best way to approach this would be to create a type or interface for that data:

解决此问题的最佳方法是为该数据创建类型或接口:

interface Dog {
  name: string
  age: number
}

Then you can write the above in this way, which is shorter:

然后,您可以通过以下方式编写上面的代码,它更短:

const dog: Dog = body.value

翻译自: https://flaviocopes.com/typescript-object-destructuring/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值