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:
我尝试添加像这样的string
和number
类型:
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/