【十月打卡】第57天 TypeScript(13)
2022/10/4 4:17:46
本文主要是介绍【十月打卡】第57天 TypeScript(13),对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
联合类型和类型保护
联合类型
联合类型使用 | 来表示
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'; }
这篇关于【十月打卡】第57天 TypeScript(13)的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-05-15PingCAP 黄东旭参与 CCF 秀湖会议,共探开源教育未来
- 2024-05-13PingCAP 戴涛:构建面向未来的金融核心系统
- 2024-05-09flutter3.x_macos桌面os实战
- 2024-05-09Rust中的并发性:Sync 和 Send Traits
- 2024-05-08使用Ollama和OpenWebUI在CPU上玩转Meta Llama3-8B
- 2024-05-08完工标准(DoD)与验收条件(AC)究竟有什么不同?
- 2024-05-084万 star 的 NocoDB 在 sealos 上一键起,轻松把数据库编程智能表格
- 2024-05-08Mac 版Stable Diffusion WebUI的安装
- 2024-05-08解锁CodeGeeX智能问答中3项独有的隐藏技能
- 2024-05-08RAG算法优化+新增代码仓库支持,CodeGeeX的@repo功能效果提升