【十月打卡】第57天 TypeScript(13)
标签:
Typescript
联合类型和类型保护
联合类型
联合类型使用 | 来表示
const value = string | number;
类型保护
- 类型断言 as
- in
interface Bird {
fly: boolean;
sing: () => void;
}
interface Dog {
fly: boolean;
bark: () => void;
}
// 类型断言 as
function handleAnimal(animal: Bird | Dog){
if(animal.fly){
(animal as Bird).sing()
}else{
(animal as Dog).bark()
}
}
// in
function judgeAnimal(animal: Bird | Dog) {
if ('sing' in animal) {
animal.sing()
} else {
animal.bark();
}
}
- typeof
function total(first: string | number, second: string | number) {
if (typeof first === 'string' || typeof second === 'string') {
return `${first}${second}`;
}
return first + second;
}
- instanceof
class Person {
constructor(public name: number) {}
}
class Purchase {
constructor(public count: number) {}
}
function addCount(first: Person | Purchase, second: Person | Purchase) {
if (first instanceof Purchase && second instanceof Purchase) {
return first.count + second.count;
}
return 100;
}
枚举类型 enum
介绍
- enum 适用于有多种状态的场景判断
- enum第一个默认是0,后面的如果没有指定,会在前面基础上加1
- enum是可以双向访问
enum Network {
ONLINE = 1,
G4,
G3,
OFFLINE,
};
console.log(Network.ONLINE) // 1
console.log(Network[1]) // 'ONLINE'
示例
- 正常的js代码
const Network = {
ONLINE: 0,
G4: 1,
G3: 2,
OFFLINE: 3,
};
function getNetworkStatus(status: number) {
if (status === Network.ONLINE) {
return 'online';
} else if (status === Network.G4) {
return '4g';
} else if (status === Network.G3) {
return '3g';
} else if (status === Network.OFFLINE) {
return 'offline';
}
return 'else';
}
- ts中使用enum来改造
enum Network {
ONLINE,
G4,
G3,
OFFLINE,
};
function getNetworkStatus(status: number) {
if (status === Network.ONLINE) {
return 'online';
} else if (status === Network.G4) {
return '4g';
} else if (status === Network.G3) {
return '3g';
} else if (status === Network.OFFLINE) {
return 'offline';
}
return 'else';
}
点击查看更多内容
为 TA 点赞
评论
共同学习,写下你的评论
评论加载中...
作者其他优质文章
正在加载中
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦