联合类型
interface Bird {
fly: boolean,
sing:()=>{}
}
interface Dog {
fly: boolean,
bark:()=>{}
}
function traingAnimal(animal: Bird | Dog) {
animal.sing() // 报错
}
联合类型只能访问到公有属性和方法。
交叉类型
多种类型的集合,联合对象将具有所联合类型的所有成员
interface People {
age: number,
height: number
}
interface Man{
sex: string
}
const xiaoman = (man: People & Man) => {
console.log(man.age)
console.log(man.height)
console.log(man.sex)
}
xiaoman({age: 18,height: 180,sex: 'male'});
类型保护
类型断言
如果明确知道对象类型,可以使用as
转换成具体对象实例。
/// 类型保护1:类型断言
function traingAnimal(animal: Bird | Dog) {
if (animal.fly) {
(animal as Bird).sing()
} else {
(animal as Dog).bark()
}
}
in语法
如果指定属性和方法在某个实例对象中,就可以在对应语句块中调用具体实例对象的方法。
/// 类型保护2:in语法
function traingAnimal(animal: Bird | Dog) {
if ('sing' in animal) {
animal.sing()
} else {
animal.bark()
}
}
typeof 语法
/// 类型保护3:typeof 语法
function traingAnimal(first:number|string,second:number|string) {
if (typeof first === 'string' || typeof second === 'string') {
return `${first}${second}`
} else {
return first + second
}
}
instanceof 语法
instanceof 做类型判断只能识别 class 对象类型而不能识别 interface 类型。
class NumberObj {
count: number
}
// 类型保护4:instanceof 语法
function addSecond(first: object | NumberObj, second: object | NumberObj) {
if (first instanceof NumberObj && second instanceof NumberObj) {
return first.count + second.count
}
return 0
}