6-ts联合类型-类型断言-交叉类型

6-ts联合类型-类型断言-交叉类型_第1张图片

//声明变量时候联合类型, 同时支持多种数据类型
let phone:number | string = '123456'
let fz = function(type:number | boolean):boolean {
  return !!type //强转
}
console.log(fz(1))

//交叉类型
interface People {
  name: string,
  age: number
}
interface Man {
  sex: number
}
const test1 = (man: People & Man):void => {
  console.log(man)
}
test1({ name: 'tom', age: 12,  sex: 1})

//类型断言
let test2 = function(num: number | string):void {
  console.log((num as string).length, 'xxx')
  console.log((num as any).length, 'yyy')
}
test2('123456789')
test2(123456789)

//window.abc = 123 //报错
//(window as any).abc = 123

 

你可能感兴趣的:(typescript,typescript)