TypeScript union types cross type type assertions

union type

let phone: number | string  = 34656
//这样写是会报错的应为我们的联合类型只有数字和字符串并没有布尔值
let myPhone: number | string  = true

Functions use union types

const fn = (strflag:number | boolean):boolean => {
    
    
     return !!strflag
}

cross type

A collection of multiple types, the union object will have all members of the types being united

interface Person {
    
    
  age: number,
  height: number
}
interface Man{
    
    
  sex: string
}
const zs = (man: Person & Man) => {
    
    
  console.log(man.age)
  console.log(man.height)
  console.log(man.sex)
}
zs({
    
    age: 18,height: 190,sex: '男'});

type assertion

  • Syntax: value as type or <type> value value as string value
interface A {
    
    
       run: string
}
 
interface B {
    
    
       build: string
}
 
const fn = (type: A | B): string => {
    
    
       return type.run
}
//这样写是有警告的应为B的接口上面是没有定义run这个属性的
interface A {
    
    
       run: string
}
 
interface B {
    
    
       build: string
}
 
const fn = (type: A | B): string => {
    
    
       return (type as A).run
}
//可以使用类型断言来推断他传入的是A接口的值

It should be noted that type assertions can only "cheat" the TypeScript compiler and cannot avoid runtime errors. On the contrary, abusing type assertions may lead to runtime errors:

Use any temporary assertion

window.a = 123
//这样写会报错因为window没有a这个东西
(window as any).a = 123
//可以使用any临时断言在 any 类型的变量上,访问任何属性都是允许的。

Guess you like

Origin blog.csdn.net/qq_52099965/article/details/127823117