TS的函数重载、类型合并、类型断言

函数重载
let list5 = [1, 2, 3, 4]

function findNum(id: number): number[]

function findNum(): number[]

function findNum(list: number[]): number[]

function findNum(ids?: number | number[]): number[] {

    if (typeof ids === 'number') {

        return list5.filter((num) => num === ids)

    }

    else if (Array.isArray(ids)) {

        return list5.concat(ids);

    }

    else {

        return list5;

    }

}
类型合并
interface People {
    name: string,
    age: number
}

interface Man {
    sex: number
}

function getUser(data: People & Man): void {
    console.log(data)
}

getUser({

    name: 'cqs',

    age: 27,

    sex: 1

})
类型断言
function funs(str: number | string): void {
    console.log((str as string).length)
}


interface A {
    a: string
}

interface B {
    b: string
}

function fun1(str: A | B) {

    console.log((str).b);

    console.log((str as B).b);

}

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