Typescript知识点速记

87 阅读1分钟

ts在线编辑

www.typescriptlang.org/play

接口定义

interface Student {
    name: string
    // 可有可无
    age?: number
    // 只读
    readonly sex: number
    // 任意值
    [_: string]: any
}

&用于缩小类型范围

常用于将string、number、symbolstring

type t = string | boolean | symbol
type n = t & string

可变元组定义

const arr: [number, number, ...any] = [1,2,"12", true]
const [one, two, ...rest] = arr

自定义守卫

用于缩小类型范围,函数返回boolean且函数签名为is

export function isRef(r: any): r is Ref {
  return !!(r && r.__v_isRef === true)
}

构造函数类型

class A {
  age: number = 12
}

type AT = new (...args: any) => A
interface AI {
  new (...args: any): A
}

const B: AT = A
const C: AI = A

模板语法

// type Greeting<T extends string> = `hello ${T}`
type Greeting<T> = `hello ${T & string}`
type Amy = 'world'
const a:Greeting<Amy> = 'hello world'

获取类型的所有key

interface A {
  name: string;
  age: number;
}
type NA = A[keyof A]

as用于重新定义key

type ResetKey<O extends object> = { 
    [K in keyof O as `${K & string}_haha`]: O[K]
}

ResetKey<{ kk: 12 }>;

as用于类型过滤

interface A {
  name: string;
  age: number;
}
type NA<T> = {
  [K in keyof T as T[K] extends string ? K: never]: T[K]
}
type TA = NA<A>

as用于定义只读数组

const arr = [1,2,3] as const

infer提取未知参数

type IFE<T> = T extends infer P ? P : never
type APP = IFE<string>

type FUNC = (params: boolean) => string
type APP2 = FUNC extends (params: infer P) => any ? P :never

类型选取

用于参数同时存在不同类型情况

type A = {
  name: 'A';
  age: number;
}

type B = {
  name: 'B';
  weight: number;
}

type C = A | B;

function printC(cArg: C) {
  if(cArg.name === 'A') {
    console.log(cArg.age)
  } else {
    console.log(cArg.weight)
  }
}

函数重载

function func<T, P>(a: T, b: P): { a: T, b: P }
function func<T>(a: T, b: void): { a: T }
function func<T, P>(a: T, b: P) {
  return { a, b }
}
console.log(func(1, 2))
console.log(func(1))

数组转联合

type union = ['a', 'b'][number]