6.联合类型&交叉类型&类型断言

57 阅读1分钟

6.联合类型&交叉类型&类型断言

1.联合类型

let phone:number | string = 17679362633
const handleBoolean = function(type:number | boolean):boolean{
    return !!type
}
console.log(handleBoolean(1))

2.交叉类型

interface People{
	name:string
	age:number
}
interface Man{
	gender:string
}
const peoples = (people:People & Man):void =>{
    console.log(people) //{ name: 'fly', age: 18, gender: '男' }
}
peoples({
    name:"fly",
    age:18,
    gender:"男"
})

3.类型断言

类型断言是一种告诉编译器变量的类型的方式,它可以在编译时确定类型,使得代码更具可读性,并且在某些情况下可以提高代码的可维护性和性能。但是,类型断言并不会改变变量的实际类型,也不能解决类型错误
const fn = (num: number | string): void => {
  console.log((num as string).length);
  console.log((<string>num).length);
};
fn("12343535432fdg");

interface A {
  run: string;
}
interface B {
  build: string;
}

const fun = (type: A | B): void => {
  console.log((<A>type).run);
};
fun({
  run: "跑",
});