typeScript 数据类型笔记
数据类型 | 元组
- 概念:就是一个规定了元素数量和每个元素类型的“数组”,而每个元素的类型,可以不相同
- 语法:
1 2
| let tup1: [string, number, boolean] = ['哈哈~~', 18, true];
|
数据类型 | 枚举

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
|
enum Gender { Boy = 1, Girl = 2, Unknown = 3 }
let usrSex: Gender = Gender.Boy;
if (usrSex == Gender.Boy) { console.log(usrSex); } else { console.log(usrSex) }
|
1 2 3 4 5 6 7 8 9 10 11 12
|
enum GunType { M4A1, AK47, Goza }
|
数据类型 | void
- 概念:void 代表没有类型,一般用在无返回值函数
- 语法
1 2 3 4 5 6 7 8 9 10
| function sayHi1(): string { return 'hi,你好啊' } let re1 = sayHi1();
function sayHi1(): void { console.log('讨厌'); } sayHi2();
|
数据类型 | 联合类型
- 要么是字符串要么是null,这个时候就可以用联合类型
1 2
| let dName: string | null = prompt('请输入小狗狗名字'); console.log('hello + dName');
|
数据类型 | 返回值和参数
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| function sayHi(): string { return 'hi~hello' } let res: string = sayHi();
function from(cityName: string): void { console.log('你来自哪里'); console.log(`我来自${cityName}`); }
from('加拿大');
|

- 函数必须定义 返回值类型,如果没有返回值, 则定义返回值类型为 void
数据类型 | 可选参数
调用
传参 函数名();
不传参 函数名(实参值);
数据类型 | 默认值
- 函数 默认值
形参1?: 类型 = 默认值1 带默认值的参数,本身也是可选参数
1 2 3
| function test(city: string = '加拿大', phone: number = 1): String { return 'yes' }
|
调用

Record
Record 用于定义一个对象的键值对
1 2 3 4 5 6 7 8 9 10 11
| interface PageInfo { title: string; }
type Page = "home" | "about" | "contact";
const nav: Record<Page, PageInfo> = { home: { title: "home" }, about: { title: "about" }, contact: { title: "contact" } };
|
Record 后面的泛型就是对象键和值的类型。
示例:比如我需要一个对象,有 ABC 三个属性,属性的值必须是数字,那么就这么写
1 2 3 4 5 6
| type keys = 'A' | 'B' | 'C' const result: Record<keys, number> = { A: 1, B: 2, C: 3 }
|
结语
每天下班累的只想躺着什么也不干,哪怕这一天其实没有很忙,但是那种疲惫却是避开肌肉筋骨,直到心神