Amumu12138头像
TypeScript学习: 基础类型(二)封面图

TypeScript学习: 基础类型(二)

1、联合类型|类型断言|交叉类型

// 类型别名

// 语法: type 定义: 类型1 | 类型2 | ...

type Numb = 1 | 2 | 3;

let num: Numb;

let numb: Numb;



type StrOrNum = string | number;

let a: StrOrNum = 1;

let b: StrOrNum = '123'



// 联合类型声明

let abc: string | number | boolean;

abc = 1;

abc = '123'

abc = false

// abc = undefined //不能将类型“undefined”分配给类型“string | number | boolean



// 联合类型判断:函数重载 + 联合类型实现

function add(a: number, b: number): number

function add(a: string, b: string): string

function add(a: number | string, b: number | string): number | string

function add(a: number | string, b: number | string): number | string {

return typeof a === 'number' && typeof b === 'number' ? a + b : `${a}${b}`

}



console.log(add(1, 2)); // 3

console.log(add('1', '2')); // '12'

console.log(add(1, '2')); // '12'



// 交叉类型:& 运算符

type User = {

name: string;

age: number;

}

type Admin = User & {

role: 'admin';

}



let admin: Admin = {

    name: 'amumu',

    age: 18,

    role: 'admin'

}



// 类型断言:as 运算符

let adminName: string = admin.name as string;

console.log(adminName); // 'amumu'

2、内置对象

// 内置对象

// 1. Math 对象

console.log(Math.PI); // 3.141592653589793

console.log(Math.random());



// 2. Date 对象

console.log(new Date());

console.log(new Date().getFullYear()); // 2026

console.log(new Date().getMonth()); // 10

console.log(new Date().getDate()); // 25

console.log(new Date().getHours()); // 14

console.log(new Date().getMinutes()); // 23

console.log(new Date().getSeconds()); // 59



// 3. String 对象

console.log('hello'.length); // 5

console.log('hello'.toUpperCase()); // 'HELLO'

console.log('hello'.toLowerCase()); // 'hello'



// 4. Number 对象(PI、random 属于 Math,不是 Number)

console.log(Number.MAX_VALUE); // 1.7976931348623157e+308

console.log(Number.isInteger(1.5)); // false



// 5. Boolean 对象

console.log(Boolean(true)); // true

console.log(Boolean(false)); // false

console.log(Boolean('')); // false

console.log(Boolean('hello')); // true

console.log(Boolean(0)); // false

console.log(Boolean(1)); // true



// 6. Array 对象

console.log(new Array());

console.log(new Array(1, 2, 3));

console.log(new Array(3, 4, 5));



// 7. Object 对象

console.log(new Object());

console.log(new Object({ name: 'amumu' }));



// 8. Function 对象

console.log(new Function());

console.log(new Function('return 1 + 2;'));

console.log(new Function('a', 'b', 'return a + b;'));

console.log(new Function('a', 'b', 'return a + b;')(1, 2)); // 3



// 9. RegExp 对象

console.log(new RegExp('hello'));

console.log(new RegExp('hello', 'i'));



// 10. Error 对象

console.log(new Error());

console.log(new Error('hello'));



// 11. Promise 对象(构造函数必须传 executor)

console.log(new Promise(() => { }));

console.log(new Promise((resolve, reject) => {

resolve('hello');

}));

console.log(new Promise((resolve, reject) => {

reject('hello');

}).catch((reason) => reason)); // 捕获 rejection,避免 unhandled rejection 让进程退出



// 12. Symbol 对象(Symbol 不能 new,直接调用)

console.log(Symbol());

console.log(Symbol('hello'));

console.log(Symbol('hello') === Symbol('hello')); // false



// 13. WeakMap 对象(key 必须是对象)

const wmKey1 = { id: 1 };

const wmKey2 = { id: 2 };

console.log(new WeakMap());

console.log(new WeakMap([[wmKey1, 'hello'], [wmKey2, 'world']]));

console.log(new WeakMap([[wmKey1, 'hello'], [wmKey2, 'world']]).get(wmKey1)); // 'hello'



// 14. WeakSet 对象(成员必须是对象)

const wsItem1 = {};

const wsItem2 = {};

console.log(new WeakSet());

console.log(new WeakSet([wsItem1, wsItem2]));

console.log(new WeakSet([wsItem1, wsItem2]).has(wsItem1)); // true



// 15. Set 对象

console.log(new Set());

console.log(new Set([1, 2, 3]));

console.log(new Set([1, 2, 3]).has(1)); // true



// 16. Map 对象

console.log(new Map());

console.log(new Map([[1, 'hello'], [2, 'world']]));

console.log(new Map([[1, 'hello'], [2, 'world']]).get(1)); // 'hello'

3、类Class

// 动物类

class Animal {

name: string

constructor(name: string) {

this.name = name;

}



sleep() {

console.log('sleep called');

}

}





// 实现接口继承

interface IAnimal {

name: string

sleep(): void

}



// 狗类

class Dog extends Animal implements IAnimal {

public name: string

constructor(name: string) {

super(name)

this.name = name;

}



sleep() {

console.log('dog sleep called');

}

}



// 测试

const dog = new Dog('大黄')

console.log(dog.name, 'name');

dog.sleep()



// 实现private、protected、public

class AnimalLst {

private name: string

// super()方法:调用父类的构造函数

constructor(name: string) {

this.name = name;

}



sleep() {

console.log('sleep called');

}

// protected属性只能在类内部访问,不能在外部访问

protected protectedName: string = 'protectedName';

// public属性可以在外部访问

public publicName: string = 'publicName';

}



// 实现super()方法:调用父类的构造函数

class DogLst extends AnimalLst {

constructor(name: string) {

super(name)

}



sleep() {

console.log('dog sleep called');

}

// static属性可以在外部访问,但是不能在类内部访问

static staticName: string = 'staticName';

// static方法可以在外部访问,但是不能在类内部访问

static staticMethod() {

console.log('static method called');

}

// 实例方法可以在外部访问

instanceMethod() {

console.log('instance method called');

}



// 实现属性age

private age: number = 0;

// 实现setter方法:设置age属性

set setAge(age: number) {

this.age = age;

}

// 实现getter方法:获取age属性

get getAge() {

return this.age;

}

}

// 测试

const animal = new AnimalLst('amumu');

// animal.name = 'amumu'; // 错误:private属性不能在外部访问

// animal.sleep(); // 错误:sleep方法不能在外部调用

console.log(animal.publicName, 'publicName'); // publicName

// console.log(animal.protectedName, 'protectedName'); // 错误:protected属性不能在外部访问



// 测试static属性和方法

console.log(DogLst.staticName, 'staticName'); // staticName

DogLst.staticMethod(); // static method called

// 测试实例方法

const dogLst = new DogLst('大黄')

dogLst.instanceMethod(); // instance method called

// 测试属性age

console.log(dogLst.getAge, 'getAge'); // 0

dogLst.setAge = 1;

console.log(dogLst.getAge, 'getAge'); // 1

4、抽象类

// 实现private、protected、public

class AnimalLst {

private name: string

// super()方法:调用父类的构造函数

constructor(name: string) {

this.name = name;

}



sleep() {

console.log('sleep called');

}

// protected属性只能在类内部访问,不能在外部访问

protected protectedName: string = 'protectedName';

// public属性可以在外部访问

public publicName: string = 'publicName';

}



// 实现super()方法:调用父类的构造函数

class DogLst extends AnimalLst {

constructor(name: string) {

super(name)

}



sleep() {

console.log('dog sleep called');

}

// static属性可以在外部访问,但是不能在类内部访问

static staticName: string = 'staticName';

// static方法可以在外部访问,但是不能在类内部访问

static staticMethod() {

console.log('static method called');

}

// 实例方法可以在外部访问

instanceMethod() {

console.log('instance method called');

}



// 实现属性age

private age: number = 0;

// 实现setter方法:设置age属性

set setAge(age: number) {

this.age = age;

}

// 实现getter方法:获取age属性

get getAge() {

return this.age;

}

}

// 测试

const animal = new AnimalLst('amumu');

// animal.name = 'amumu'; // 错误:private属性不能在外部访问

// animal.sleep(); // 错误:sleep方法不能在外部调用

console.log(animal.publicName, 'publicName'); // publicName

// console.log(animal.protectedName, 'protectedName'); // 错误:protected属性不能在外部访问



// 测试static属性和方法

console.log(DogLst.staticName, 'staticName'); // staticName

DogLst.staticMethod(); // static method called

// 测试实例方法

const dogLst = new DogLst('大黄')

dogLst.instanceMethod(); // instance method called

// 测试属性age

console.log(dogLst.getAge, 'getAge'); // 0

dogLst.setAge = 1;

console.log(dogLst.getAge, 'getAge'); // 1

5、元组

/**

* 定义: 元组就是定长的数组

* 原理: 元组的存储效率比较好,因为元组是固定的,不会出现扩容现象,

* 使用场景: 数组数量固定的情况

* 语法: let h: [string, string]

*/



let area: [number, number]

area = [5, 5]

area = [0] // 提示不能将类型“[number]”分配给类型“[number, number]”。源具有 1 个元素,但目标需要 2 个

area = ['1', '2'] // 提示不能将类型“string”分配给类型“number”



// 元组的使用场景

// 1. 数组数量固定的情况

// 2. 数组元素类型不固定的情况

// 3. 数组元素类型固定的情况

let arr0: [number, string, boolean]

arr0 = [1, '2', Boolean(true)]

arr0 = [1, '2', Boolean(false)]

6、枚举类型

// 语法: enum 枚举名称 {

// 成员1,

// 成员2

//}



// 数字枚举

enum Color {

red = 0,

green = 1,

yellow

}



console.log(Color.red, 'red'); // 0

console.log(Color.green, 'green'); // 1

console.log(Color.yellow, 'yellow'); // 2



// 字符串枚举

enum Gener {

MALE = 'male',

FEMALE = 'female'

}



console.log(Gener.MALE, 'MALE'); // male

console.log(Gener.FEMALE, 'FEMALE'); // female



// 异构枚举

enum Gener2 {

MALE = 6,

FEMALE = 'female'

}



console.log(Gener2.MALE, 'MALE'); // 6

console.log(Gener2.FEMALE, 'FEMALE'); // female



// 接口枚举

interface Gener3 {

MALE: string;

FEMALE: string;

}



const Gener3: Gener3 = {

MALE: 'male',

FEMALE: 'female'

}



console.log(Gener3.MALE, 'MALE'); // male

console.log(Gener3.FEMALE, 'FEMALE'); // female



// const 枚举

const enum Gener4 {

MALE = 'male',

FEMALE = 'female'

}

console.log(Gener4.MALE, 'MALE'); // male

console.log(Gener4.FEMALE, 'FEMALE'); // female

7、类型推论|类型别名

// 类型别名

// 语法: type 定义: 类型1 | 类型2 | ...

type Numb = 1 | 2 | 3;

let num: Numb;

let numb: Numb;



type StrOrNum = string | number;

let a: StrOrNum = 1;

let b: StrOrNum = '123'

8、never类型

// never 类型

/**

* 定义: never 类型表示 never 类型的值, never 类型的值是 never 类型的唯一值

* 原理: never 类型的值是 never 类型的唯一值, never 类型的值是 never 类型的唯一值

* 使用场景: 1. 函数 never 类型的参数 2. 函数 never 类型的返回值

*/

function neverFunc(): never {

throw new Error('never 类型的函数')

}



// never 类型的参数

function neverFunc2(param: never): never {

console.log(param);

throw new Error('never 类型的函数2')

}



// 死循环

function neverFunc3(): never {

while (true) {

console.log('死循环')

}

}

转载自 CSDN-专业IT技术社区

原文链接:https://blog.csdn.net/Amumu12138/article/details/171478132

文章来源转载

评论

评论列表

微信小程序
QQ小程序

关于作者

点赞数:0
关注数:0
粉丝:0
文章:0
关注标签:0
加入于:--