Skip to content

联合类型类型断言交叉类型

联合类型

typescript
let phone1: number | string = '110'
let phone2: number | string = 110


// 当后台返回数据不知道为1|0还是true|false时,可以直接用以下这种方式处理
let fn = function (type: number | boolean): boolean {
    // 两次!使得传入的1|true为true。传入的0|false为false
    return !!type
}

fn(1)
// 🚀 ~ file: index.ts:11 ~ fn(1): true
console.log("🚀 ~ file: index.ts:11 ~ fn(1):", fn(1))

fn(false)
// 🚀 ~ file: index.ts:13 ~ fn(false): false
console.log("🚀 ~ file: index.ts:13 ~ fn(false):", fn(false))

类型断言

typescript
let fn = function (num: number | string): void {
    console.log("🚀 ~ file: index.ts:2 ~ num:", (num as string).length)
}
fn('12345')


interface A {
    run: string
}
interface B {
    build: string
}
let fn = (type: A | B) => {
    console.log((type as A).run)
   `    // 也可以 console.log((<A>type).run)
}
// 用以下输出会输出underfined,除非把build改为run
fn({
    build:'123'
})


//临时断言
(window as any).abc=123


//无效的断言
const fn=(type:any):boolean=>{
    return type as boolean
}
fn(1)
// 🚀 ~ file: index.ts:10 ~ fn(0): 0,说明这样使用是无效的
console.log("🚀 ~ file: index.ts:10 ~ fn(0):", fn(1))

交叉类型

typescript
interface People {
    name: string
    age: number
}

interface Man {
    sex: number
}

// 相当于把People和Man里的属性合并
const rarrot = (man: People & Man): void=> {
    console.log(man);
}

rarrot({
    name: 'rarrot',
    age: 66,
    sex: 0
})

Released under the MIT License.