【十月打卡】第57天 TypeScript(13)
標(biāo)簽:
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';
}
點(diǎn)擊查看更多內(nèi)容
為 TA 點(diǎn)贊
評(píng)論
評(píng)論
共同學(xué)習(xí),寫(xiě)下你的評(píng)論
評(píng)論加載中...
作者其他優(yōu)質(zhì)文章
正在加載中
感謝您的支持,我會(huì)繼續(xù)努力的~
掃碼打賞,你說(shuō)多少就多少
贊賞金額會(huì)直接到老師賬戶
支付方式
打開(kāi)微信掃一掃,即可進(jìn)行掃碼打賞哦