TypeScript 联合类型和类型保护
TypeScript学习笔记
联合类型
关键符好是 | 是联合类型
interface SDQ { anjiao: boolean; say: () => {}; }
interface SDZ { anjiao: boolean; skill: () => {}; }
function subject(Number: SDQ | SDZ) { if(Number.anjiao){ (Number as SDZ).skill }else{ (Number as SDQ).say } }
|
类型断言
类型保护/类型断言
as语法
interface SDQ { anjiao: boolean; say: () => {}; }
interface SDZ { anjiao: boolean; skill: () => {}; }
function subject(Number: SDQ | SDZ) {
if(Number.anjiao){ (Number as SDZ).skill }else{ (Number as SDQ).say } }
|
in语法
function subjectTwo(Number: SDQ | SDZ) {
if ("skill" in Number) { Number.skill(); } else { Number.say(); } }
|
typeof语法
function sdq(first: string | number, second: string | number) {
if (typeof first === "string" || typeof second === "string") { return `${first}${second}`; } return first + second; }
|
instanceof语法
function sdz(first: object | NumberObj, second: object | NumberObj) { if (first instanceof NumberObj && second instanceof NumberObj) { return first.count + second.count; } return 0; }
|
作者: 我叫史迪奇
本文来自于:
https://sdq3.link/TypeScript-Union-type-protection.html博客内容遵循 署名-非商业性使用-相同方式共享 4.0 国际 (CC BY-NC-SA 4.0) 协议