一.ts基础类型
- 布尔,数字,字符串类型
const bol: boolean = false //布尔
const str: string = '我是字符串类型' //字符串
const num: number = 1998
console.log(bol, str, num)
- 数组类型
let arr1: number[] = [1, 1, 1, 1]
let arr2: Array<number> = [2, 2, 2, 2]
let arr3: (number | string)[] = [1, '2']
let arr4: Array<string | number> = [1, '2']
console.log(arr1, arr2, arr3, arr4);
- 元组
let tuple: [string, number, boolean] = ['1', 2, true]
let tuple1: [string] = ['1']
tuple1.push('2') //// 元组中增加数据,只能增加元组中存放的类型
console.log(tuple, tuple1)
- any类型
//any 类型不对任何数据进行检测
const any1: any = [1, '2', 1, true, { obj: 'name' }]
- null 和 undefined
/**
* null 和 undefined 是任何类型的子类型 在tsconfig.json 文件中
* strictNullChecks=true 则无法将null和undefined 进行赋值
*/
let nullOrUndefined: string | boolean;
// 必须把 strictNullChecks 关掉才可以赋值操作
nullOrUndefined = null
nullOrUndefined = undefined
- 枚举类型
- 数字枚举
// 数字枚举 如何不给 Up = 1, 这默认从0开始
enum Direction {
Up,
Down,
Left,
Right,
}
enum Direction1 {
Up = 1,
Down,
Left,
Right,
}
console.log(Direction, Direction1, '数字枚举');
2.字符串枚举
enum Direction2 {
Up = "UP",
Down = "DOWN",
Left = "LEFT",
Right = "RIGHT",
}
console.log(Direction2);
- 异构枚举
// 异构枚举
enum USER_ROLE {
USER = 'user',
ADMIN = 1,
MANAGER,
}
console.log(USER_ROLE);
4.常量枚举
const enum USER_ROLE1 {
USER,
ADMIN,
MANAGER,
}
console.log(USER_ROLE.USER, '常量枚举')// console.log(0 /* USER */);
enum E1 {
X,
Y,
Z,
}
console.log(E1.X, '常量枚举')
- void类型
let voide: void;
// void 只能接受null,undefined。一般用于函数的返回值
voide = undefined;
//strictNullChecks=true 严格模式下不能将null赋予给void
voide = null
- never类型
// 任何类型的子类型 never(最小值了在它下面没有儿子类型了) 代表不会出现任何值,不能把其他类型赋值给never
function name(params: string): never {
// console.log(1111);
throw new Error("1111");
}
function fn(x: number | string): never {
if (typeof x == 'number') {
} else if (typeof x === 'string') {
} else {
console.log(x); // never
}
}
- Symbol类型
// Symbol表示独一无二
const s1: symbol = Symbol('1')
const s2: symbol = 1
console.log(s1 === s2) //false;
- BigInt类型
// BigInt 类型
const num1 = Number.MAX_SAFE_INTEGER + 1;
const num2 = Number.MAX_SAFE_INTEGER + 2;
console.log(num1, num2, num1 == num2)// true
let max: bigint = BigInt(Number.MAX_SAFE_INTEGER)
console.log(max + BigInt(1), max + BigInt(2), max + BigInt(1) === max + BigInt(2), 'BigInt类型') //fasle
- object对象类型
// object表示非原始类型
let create = (obj: object): void => { }
create({});
create([]);
create(function () { })
create(1)