Skip to content

泛型和内置类型

  • 泛型用法
ts
// 案例1
function echo<T>(arg: T): T {
    return arg
}
const result = echo(123)


// 案例2
function swap<T,U>(arr: [T,U])[U,T] {
    return [arr[1], arr[0]]
}
swap(['str', 123])

// 案例3
interface GithubResp {
    name: string;
    count: number;
}

function withApi<T>(url: string): Promise<T> {
    return fetch(url).then(resp => resp.json())
}
// 此时resp就是GithubResp类型了
withApi<GithubResp>('github.user').then(resp => {})
  • 【type】类型别名
ts
type PlusType = (x: number, y:number) => number
let sum2: PlusType

sum2 = function(x,y){
    return x
}
sum2(1,2)
  • 【&】交叉类型
ts
// 获取类型的并集
interface IName {
    name: string
}
type IPerson = IName & {age: number}
let person: IPerson = {name: 'xxx', age: 1221}
  • 【|】联合类型
ts
// numOrStr是两种类型之一
// 此时可以使用number 和 string类型共有的方法
// 使用非共有的属性会报错,比如numOrStr.length
let numOrStr: number | string
  • 【as】类型断言
ts
// 断言后可以使用联合类型里非共有的属性
function getLength(input: number | string) {
    const str = input as string
    if(str.length) {
        return str.length
    } else {
        const num = input as number
        return number.toString().length
    }
}
  • 【Partail】将类型变成可选类型
ts
interface IPerson {
    name: string
    age: number
}
// 使IPerson里的属性都变成可选的了
type PersonOptional = Partial<IPerson>
let person: PersonOptional = {
    name: '111'
}
  • 【keyof】
ts
interface Country {
    name: string
    area: number
}

// keys的类型为name|area
type keys = keyof Country


const a = 123 // 此时a是常量类型123
let key: Keys = 'name' // 此处Keys只从name或者area取其中一个

type nameType = Country['name'] // nameType类型为string

// 把Keys当对象用
// 相当于Test = {
//    name: string
//    area: number
// }
type Test = {
    [key in Keys]: Keys[key]
}
  • 【extends】
ts
interface IWithLength {
    length: number
}

// 利用extends限制泛型,必须传入含length的类型,不然会报错
function echoWithArr<T extends IWithLength>(arg: T): T{
    return arg.length
}

// T如果是null | undefined的子集,则返回never,否则返回T类型
type NonType<T> = T extends null | undefined ? never : T

苏ICP备20040768号