2

TypeScript 中的对象重构

 1 week ago
source link: https://www.fly63.com/article/detial/12704
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

更新日期: 2024-04-03阅读: 463标签: 对象分享

扫一扫分享

对象重构是 ES 6 的一项强大功能,可帮助开发人员编写更简洁的代码。它允许我们将 JavaScript 对象中的属性提取到变量中。

说到 TypeScript 中的对象重构,下面的语句不起作用。

const { title: string, comments: number } = blog

技术上讲,它的工作方式是将对象的标题属性赋值给名为 string 的变量,并将注释属性赋值给数字变量。之所以会出现这种情况,是因为 JavaScript 假定我们要对变量进行重组和重命名,这是 ES6 的有效语法

在 TypeScript 中进行对象重构的正确方法是:

const { title, comments } : { title: string; comments: number }  = blog

另一种方法是使用接口或类型声明:

interface Blog {
title: string
comments: number
}

const { title, comments }: Blog = blog

默认情况下,类型通常是推断出来的,因此通常不需要这种对象重构。

链接: https://www.fly63.com/article/detial/12704


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK