TypeScript 中的数据类型

TypeScript 中的数据类型

本文讲解了 TypeScript 中的数据类型。

YouTube Video

TypeScript 中的数据类型

TypeScript 提供了多种数据类型。这使您可以为变量、函数参数和返回值指定严格的类型。以下是主要的数据类型及其用法。

基本类型

number类型

1let age: number = 25;
2console.log(age);          // Outputs: 25
3console.log(typeof age);    // Outputs: number
  • number 是一种用于处理数值的类型,包括整数和浮点数(小数)。处理超出某些限制的数值时会导致 Infinity(无穷大)或 NaN(非数字)。
1// Decimal calculations
2console.log(0.1 + 0.2 === 0.3); // false
3console.log(0.1 + 0.2); // 0.30000000000000004
4
5// Calculations with large numbers
6console.log(9007199254740991 + 1); // correct value
7console.log(9007199254740991 + 2); // incorrect value
  • 在 TypeScript 中,数字表示为浮点数。这可能导致计算结果出现轻微的不准确。

  • 当需要精确计算(如财务金额)时,必须避免这样的舍入错误。例如,可以使用 BigInttoFixed(),或者使用诸如 decimal.js 的库来调整小数位数。

string类型

string 类型用于处理文本数据。

1let greeting: string = "Hello, TypeScript!";
2console.log(greeting);     // Outputs: Hello, TypeScript!
3console.log(typeof greeting);  // Outputs: string

boolean(逻辑类型)

boolean 类型具有两个值:truefalse

1let isOpen: boolean = true;
2console.log(isOpen);       // Outputs: true
3console.log(typeof isOpen);    // Outputs: boolean

null 和 undefined

null 表示“不存在的值”,undefined 表示“未定义的值”。

1let emptyValue: null = null;
2let notDefined: undefined = undefined;
3
4console.log(emptyValue);       // Outputs: null
5console.log(typeof emptyValue);    // Outputs: object (JavaScript specification)
6
7console.log(notDefined);       // Outputs: undefined
8console.log(typeof notDefined);    // Outputs: undefined

Array

在 TypeScript 中,您可以指定数组元素的类型。number[] 是一个数字数组,string[] 是一个字符串数组。

1let numbers: number[] = [1, 2, 3, 4];
2console.log(numbers);        // Outputs: [1, 2, 3, 4]
3console.log(typeof numbers); // Outputs: object
4
5let words: string[] = ["TypeScript", "JavaScript"];
6console.log(words);          // Outputs: ["TypeScript", "JavaScript"]
7console.log(typeof words);   // Outputs: object

元组 (Tuple)

元组是一种包含不同类型元素的数组。

1let person: [string, number] = ["Alice", 30];
2console.log(person);         // Outputs: ["Alice", 30]
3console.log(typeof person);  // Outputs: object

枚举 (Enum)

enum 定义了一组命名常量。

1enum Color {
2    Red,
3    Green,
4    Blue
5}
6
7let favoriteColor: Color = Color.Green;
8console.log(favoriteColor);  // Outputs: 1 (Defaults start from 0)
9console.log(typeof favoriteColor); // Outputs: number

any

any 类型可以包含任何类型的值,用于禁用类型检查时。

1let anything: any = "Hello";
2console.log(anything);       // Outputs: Hello
3console.log(typeof anything);    // Outputs: string
4
5anything = 42;
6console.log(anything);       // Outputs: 42
7console.log(typeof anything);    // Outputs: number

联合类型 (Union Type)

使用联合类型,您可以定义可以持有多种类型之一的变量。

1let identifier: number | string = "ID_12345";
2console.log(identifier);     // Outputs: ID_12345
3console.log(typeof identifier);  // Outputs: string
4
5identifier = 12345;
6console.log(identifier);     // Outputs: 12345
7console.log(typeof identifier);  // Outputs: number

总结

  • numberstringboolean:基本类型。
  • nullundefined:特殊值。
  • 数组:一个带有类型注释的数组。
  • 元组:一个包含不同类型元素的数组。
  • 枚举:一种枚举类型。
  • any:任意类型。
  • 联合:一个可以取多种类型之一的变量。

通过使用这些数据类型,TypeScript 增强了类型安全性,从而更容易在开发过程中防止错误。

包装对象

TypeScript 中的包装对象是自动创建的对象,用于将原始数据类型视为对象。原始类型支持轻量且快速的操作,而对象类型具有方法和属性,从而实现更丰富的操作。

在 JavaScript(以及 TypeScript)中,有与原始类型如 stringnumberboolean 对应的包装对象。它们分别通过名为 StringNumberBoolean 的构造函数创建。

以下是包装对象的示例。

字符串对象

String 对象为字符串提供了属性和方法。

1let strPrimitive: string = "Hello, World!";
2let strObject: String = new String("Hello, World!");
3
4console.log(strPrimitive);         // Outputs: Hello, World!
5console.log(typeof strPrimitive);  // Outputs: string
6
7console.log(strObject);            // Outputs: [String: 'Hello, World!']
8console.log(typeof strObject);     // Outputs: object

功能:

  • 与原始 string 不同,String 对象通过 typeof 被视为 object
  • 在操作字符串或调用字符串方法时,包装对象非常有用。

数字对象

Number 对象为数字提供了属性和方法。

1let numPrimitive: number = 42;
2let numObject: Number = new Number(42);
3
4console.log(numPrimitive);         // Outputs: 42
5console.log(typeof numPrimitive);  // Outputs: number
6
7console.log(numObject);            // Outputs: [Number: 42]
8console.log(typeof numObject);     // Outputs: object

功能:

  • Number 对象作为数字的包装器,包含用于数值操作的方法(例如 toFixed)。

布尔对象

Boolean 对象为布尔值提供了属性和方法。

1let boolPrimitive: boolean = true;
2let boolObject: Boolean = new Boolean(true);
3
4console.log(boolPrimitive);        // Outputs: true
5console.log(typeof boolPrimitive); // Outputs: boolean
6
7console.log(boolObject);           // Outputs: [Boolean: true]
8console.log(typeof boolObject);    // Outputs: object

功能:

  • Boolean 对象是用来包装原始 boolean 类型的,并被视为 object

包装对象与原始类型之间的区别

由于包装对象被视为对象,性能会略有下降,但由于添加了属性和方法,功能操作更多。此外,在使用 ===== 进行比较时存在差异。

1let numPrimitive: number = 123;
2let numObject: Number = new Number(123);
3
4console.log('==  : ', numPrimitive == numObject);  // Outputs: true (Value comparison)
5console.log('=== : ', numPrimitive === numObject); // Outputs: false (Due to differing types)

功能:

  • == 比较值,而 === 严格比较值和类型。=== 在比较包装对象和原始类型时返回 false

类型转换

在 TypeScript 中,正确管理 隐式显式类型转换 很重要。

隐式类型转换

  • 在 TypeScript 中,应尽量避免隐式类型转换以确保类型安全。
1const result: string = 5 + "5"; // "55" (the number is converted to a string)
2
3console.log(result);
  • 在这个例子中,数字 5 被隐式转换为字符串,结果是字符串 "55"

显式类型转换

  • 在 TypeScript 中,使用类型注解或类型转换函数可以安全地进行类型转换。
1const num: string = "123";
2const convertedNum: number = Number(num); // Converts "123" to the number 123
3
4console.log(typeof num);
5console.log(typeof convertedNum);
  • 在这个例子中,使用 Number() 函数将字符串 "123" 显式转换为数字 123

类型检查

在 TypeScript 中,可以使用 typeof 运算符检查变量的数据类型。

 1// Output: The type of 42 is: number
 2console.log('The type of 42             is:', typeof 42);
 3
 4// Output: The type of 42 is: bigint
 5console.log('The type of 42n            is:', typeof 42n);
 6
 7// Output: The type of "hello" is: string
 8console.log('The type of "hello"        is:', typeof "hello");
 9
10// Output: The type of true is: boolean
11console.log('The type of true           is:', typeof true);
12
13// Output: The type of undefined is: undefined
14console.log('The type of undefined      is:', typeof undefined);
15
16// Output: The type of null is: object
17console.log('The type of null           is:', typeof null);
18
19// Output: The type of Symbol() is: symbol
20console.log('The type of Symbol()       is:', typeof Symbol());
21
22// Output: The type of {} is: object
23console.log('The type of {}             is:', typeof {});
24
25// Output: The type of function () {} is: function
26console.log('The type of function () {} is:', typeof function () {});
  • 在 TypeScript 中,可以使用 typeof 检查类型,但为了更精确的类型检查,也推荐使用 instanceofis 操作符。

总结

  • 包装对象 被视为对象,因为它们为原始类型提供了额外的方法和属性。
  • StringNumberBoolean 是包装对象的典型示例。
  • 与原始类型不同,包装对象通过 typeof 被识别为 object

您可以在我们的YouTube频道上使用Visual Studio Code跟随上述文章进行学习。 请也查看我们的YouTube频道。

YouTube Video