TypeScript 的基础知识
在我们之前的文章中,我们学习了 TypeScript 的基础知识,如果你还没有读过,请在阅读本文之前先阅读一下。
1- 和我一起学习 TypeScript - 1
枚举
枚举提供了一种定义一组命名常量的方法。默认情况下,枚举值以 0 开头,但我们可以覆盖它们。
enum Color { Red = "RED", Green = "GREEN", Blue = "BLUE", }; const getColorMessage = (color: Color): string => { return You selected ${color}; }; console.log(getColorMessage(Color.Red));
数组
typescript 中的数组允许您定义相同类型元素的集合,您可以将它们视为某种列表,即使在 python 中它也被称为列表类型。
const numbers: number[] = [1, 2, 3, 4]; numbers.push(5); console.log(numbers); now if I try to add a string in numbers array typescript will complain number.push("five") // type string is not assignable to type number
元组
元组是 TypeScript 中的一种特殊数组类型,允许您定义具有固定大小和类型的数组。当我们确切知道数据的形状时,可以使用元组,然后通过使用元组,我们将提高读取数据的性能。
const user: [number, string] = [1, "Alice"]; console.log(user);
目的
TypeScript 中的对象允许您使用类型定义对象的结构。我们可以像这样对对象进行类型化,有关类型别名主题中的对象的更多信息
const user: { id: number; name: string } = { id: 1, name: "Alice" }; console.log(user.name);
类型别名
类型别名允许你在 TypeScript 中定义自定义类型,以提高代码重用性和可读性。现在我们可以将对象类型化为类型别名“UserType”
注意:在实际项目中不要使用诸如类型之类的词语。
type UserType = { id: number; name: string; }; const user: UserType = { id: 1, name: "Alice" }; console.log(user.id);
可选属性
可选属性允许您定义可能存在或不存在的对象属性。在我们之前的例子中,如果我们认为用户只有 id 和 name,则可能存在或不存在。我们可以在 `:` 之前添加 `?` 来表示这是一个可选属性
type UserType = { id: number; name?: string; }; const user: User = { id: 1 }; console.log(user.name ?? "Name not provided");
缩小/类型保护
类型保护允许您在特定代码块中缩小值的类型。我们知道用户名是可选属性,如果我们现在尝试打印用户名,它将显示未定义,我们不想向客户显示,因此在显示用户名之前,我们要确保用户名是字符串
if (typeof user.name == 'undefined') { console.log("Welcome", user.name) } else { console.log("Welcome Guest") }
好的,朋友们,在下一篇文章中我们将开始介绍函数和类型断言。