联合类型
let phone :number | string = 13987121814 //或者 '0871-3752'
function setBoolean (type:number|boolean):boolean {
return !!type
}
let res1 = setBoolean(1)
console.log(res1)//true 0的时候为false
let res2 = setBoolean(false)
console.log(res2) //false true的时候为true
交叉类型
interface Pople{
name:string,
age:number
}
interface Man{
sex:number
}
const setMan = (man:Man & Pople) :void => {
console.log(man)
}
setMan({
name:'小芳',
age:18,
sex:0
}) //{ name: '小芳', age: 18, sex: 0 }
断言类型
let getLength =function (num:number|string) :void {
// console.log(num.length)//报错,因为number不存在length属性
//断言
console.log((num as string).length)
}
getLength('12456')//5
getLength(12345)//undefined
const fnn = (type:any):boolean => {
return type as boolean
}
const aa = fnn(1)
console.log(aa) //1 只能欺骗编译器,对运行的结果不产生影响,不能滥用断言