如何进行类型约束
- 仅需要对
变量、函数参数、函数返回值进行约束,variable:type形式 - TypeScript 很多时候可以完成类型推导
- any:表示任何类型,TS 不会对 any 进行类型检测
基本类型
| 类型 | 描述 |
|---|---|
| string | 字符串 |
| number | 数字 |
| boolean | 布尔 |
| null 或 undefined | 空,null 和 undefined 为其他类型的子类型,所以默认情况下其他类型赋值为 null 或 undefined 不会报错 |
| Array<类型>或类型[] | 数组 |
| object | 对象,无法对对象属性值进行类型约束 |
其他常用类型
| 类型 | 描述 |
|---|---|
| 联合类型 | 多各类型取其一,格式:类型 1 | 类型 2 |
| void | 多用于函数返回值,函数无返回值 |
| never | 多用于函数返回值,代码永远不会结束。如 throw error、死循环 |
| 字面量类型 | 变量的取值范围只能是字面量类型值。如 let genger: "男"|"女" |
| 元祖类型(Tuple) | 一个固定长度的数组,且数组每个元素的类型固定 |
| any 类型 | any 类型可以避免类型检查,所以 any 类型数据可以赋值给任意类型变量 |
类型别名
格式:type 自定义类型名 = 类型
type Gender = "男" | "女";
type Person = {
name: string;
age: number;
gender: Gender;
};
let users: Person[] = [
{
name: "zhangsan",
age: 19,
gender: "男",
},
{
name: "lisi",
age: 18,
gender: "女",
},
]; 类型保护
通过 typeof 来确定变量类型,开启类型保护
函数相关约束
函数重载
在函数实现之前,对函数调用的多种情况进行声明
function combine(a: number, b: number): number;
function combine(a: string, b: string): string;
function combine(a: number | string, b: number | string): number | string {
if (typeof a === "number" && typeof b === "number") return a * b;
else if (typeof a === "string" && typeof b === "string") return a + b;
}
let num = combine(1, 2); 参数可选
通过给参数名添加问好,使参数变为可选。可选参数必须是参数列表的末尾
function sum(a: number, b: number, c?: number) {
if (c) return a + b + c;
return a + b;
}
let num1 = sum(1, 2);
let num2 = sum(1, 2, 3); 课后作业
设计一副扑克牌,要求如下:
- 不包含大小王(54 张)
- 能后创建扑克牌
- 能后打印扑克牌
type Color = "♦️" | "♣️" | "♥️" | "♠️";
type NormalCar = {
color: Color;
mark: number;
};
type Deck = NormalCar[];
function createDeck(): Deck {
let result: Deck = [];
for (let i = 1; i <= 13; i++) {
result.push(
{
mark: i,
color: "♠️",
},
{
mark: i,
color: "♣️",
},
{
mark: i,
color: "♥️",
},
{
mark: i,
color: "♦️",
}
);
}
return result;
}
function printDeck(deck: Deck) {
let map = {
1: "A",
11: "J",
12: "Q",
13: "K",
};
let result = deck.reduce((pre, card, index) => {
if (!(card.mark in map)) pre += card.color + card.mark + "\t";
else pre += card.color + map[card.mark] + "\t";
if ((index + 1) % 4 === 0) pre += "\n";
return pre;
}, "");
console.log(result);
}
const deck = createDeck();
printDeck(deck); 
京公网安备 11010502036488号