TypeScript 是 JavaScript 的一个超集,添加了静态类型、接口和类等其他语言特性。它提供了强大的类型系统,允许在编译时捕获许多常见的错误。以下是 TypeScript 中的一些基础类型及其使用方法的介绍:
Number
- 与 JavaScript 中的数字相同。
- 使用方法:直接赋值。
let num: number = 10;
String
- 用于表示文本数据。
- 使用方法:使用引号赋值。
let str: string = "Hello, TypeScript!";
Boolean
- 表示逻辑值:
true
或false
。 - 使用方法:直接赋值。
- 表示逻辑值:
let isTrue: boolean = true;
Array
- 用于表示有序的元素集合。
- 使用方法:使用方括号或
Array<T>
语法。
let arr1: number[] = [1, 2, 3];
let arr2: Array<string> = ["a", "b", "c"];
Tuple
- 表示一个已知元素数量和类型的数组。
- 使用方法:在方括号中指定元素的类型。
let x: [string, number] = ["hello", 10]; // 正确
x[0] = "world"; // 正确
x[1] = 20; // 正确
x[2] = true; // 错误,因为元组只有两个元素
Enum
- 用于定义数值集合。
- 使用方法:使用
enum
关键字。
enum Color {Red, Green, Blue}
let c: Color = Color.Green;
Any
- 当你不确定一个变量的类型时,可以使用
any
类型。 - 使用方法:直接赋值。
- 当你不确定一个变量的类型时,可以使用
let notSure: any = 4;
notSure = "maybe a string instead";
notSure = false; // okay, definitely a boolean
Void
- 表示没有任何类型返回值的函数。
- 使用方法:在函数返回类型处使用。
function warnUser(): void {
console.log("This is my warning message");
}
Null 和 Undefined
- 在 TypeScript 中,
null
和undefined
是两种不同的类型。默认情况下,它们是所有类型的子类型。但你可以使用--strictNullChecks
编译选项来更严格地检查它们。 - 使用方法:直接赋值或检查。
- 在 TypeScript 中,
let u: undefined = undefined;
let n: null = null;
- Never
- 表示的是那些永不存在的值的类型。
- 使用方法:通常用于错误处理函数或无限循环的函数。
function error(message: string): never {
throw new Error(message);
}
- Object
- 用于非原始值(即除 number,string,boolean,symbol,null 或 undefined 之外的值)。
- 使用方法:直接赋值或定义对象的形状。
let obj: object = {}; // 一个空对象
interface Person {
name: string;
age: number;
}
let person: Person = {
name: "Alice",
age: 25
};
这些只是 TypeScript 中的基础类型,实际上 TypeScript 还提供了许多其他高级类型,如联合类型、交叉类型、类型别名、映射类型等,这些都可以帮助你更精确地描述你的数据和函数。