Typescript 笔记

788 阅读3分钟

刚开始学typescript,有点懵,留个笔记记录下常用的类型方法,方便后续查找

接口

首字母要大写,加?表示参数可选

// 声明array
interface Arr {
    [index: number]: string
}

Array<{name:string,age?: number}>

// 声明一个任意类型的Object
interface Obj {
    [index: number]: string
}

// 声明制定key值的Object
interface Obj {
    key: string
}

继承使用extends

interface A {
    a: string
}

interface B extends A {
    b: string
}

// 此时 B的类型如下
type B = {
    a: string
    b: string
}

  • 类在声明时,必须要有constructor进行初始化赋值
  • 类里面的变量可用以下几个修饰符进行修饰,默认使用的是public
    • public 公有
    • private 私有-只能在声明它的类中使用
    • protected 允许继承的实例访问
    • readonly 只读
class A {
  public name: string
  private age: number
  protected sex: '男' | '女'

  constructor(name: string, age: number, sex: '男' | '女') {
    this.name = name
    this.age = age
    this.sex = sex
  }
}

class B extends A {
  public height: number
  readonly readonly: string
  
  constructor(height: number,name: string,age: number, sex: '男' | '女') {
    super(name, age, sex)
    this.height = height
    this.readonly = '我是只读的'
  }
  
  changeSex() {
    this.sex = '男' // 可以修改
  }
  // 此处会报错
  changeReadonly() {
    this.readonly = '尝试修改' // 无法分配到 "readonly" ,因为它是只读属性
  }
}

const ZhangSan = new B(160, '张三', 18, '男')
// 此处会报错
ZhangSan.age // 属性“age”为私有属性,只能在类“A”中访问
// 此处会报错
ZhangSan.sex = '女' // 属性“sex”受保护,只能在类“A”及其子类中访问

函数

函数的剩余参数,可以通过...来获取

function buildName(firstName: string, ...restOfName: string[]) {
  return firstName + " " + restOfName.join(" ");
}

let employeeName = buildName("Joseph", "Samuel", "Lucas", "MacKinzie");

泛型

function identity<T>(arg: T): T {
    return arg;
}

// 1 指定类型
let output = identity<string>("myString");  // type of output will be 'string'
// 2 无需指定,自动判断
let output = identity("myString");

// 如果是数组时,按如下方式指定T[] 或者 Array<T>
function loggingIdentity<T>(arg: T[]): T[] {
    console.log(arg.length);  // Array has a .length, so no more error
    return arg;
}

定义泛型T表明,<>为声明,我们定义了泛型函数后,可以用两种方法使用。

在类和接口中使用

interface GenericIdentityFn<T> {
    (arg: T): T;
}

class GenericNumber<T> {
    zeroValue: T;
    add: (x: T, y: T) => T;
}

枚举

//数字枚举,若不设置=1,则会从0开始+1自增
enum Direction {
    Up=1,
    Down,
    Left,
    Right,
}
// 普通枚举
enum Response {
    No = 0,
    Yes = 1,
}

// 使用的好处, 可以尽量消除魔法字符串
Direction.Down
Response.No

辅助函数

Partial

将所有值变成可选

interface Todo {
    title: string;
    description: string;
}

Partial<Todo>
{
    title?: string;
    description?: string;
}

Readonly

将所有值变成只读

Record<K,T>

生成一个key为K的对象类型,将T类型赋予里面的key

interface PageInfo {
    title: string;
}

type Page = 'home' | 'about' | 'contact';

Record<Page, PageInfo>
{
    home: { title: string },
    about: { title: string },
    contact: { title: string },
};

Pick<T,K>

自定义选择属性

interface Todo {
    title: string;
    description: string;
    completed: boolean;
}

Pick<Todo, 'title' | 'completed'>;
{
    title: string;
    completed: boolean;
}

Omit<T,K>

自定义删除几个属性

interface Todo {
    title: string;
    description: string;
    completed: boolean;
}

Omit<Todo, 'description'>;
{
    title: string;
    completed: boolean;
}

Exclude<T,U>

通过排除来生成

type T0 = Exclude<"a" | "b" | "c", "a">;  // "b" | "c"
type T1 = Exclude<"a" | "b" | "c", "a" | "b">;  // "c"
type T2 = Exclude<string | number | (() => void), Function>;  // string | number

NonNullable

排除类型中的null和undefined

type T0 = NonNullable<string | number | undefined>;  // string | number
type T1 = NonNullable<string[] | null | undefined>;  // string[]

Parameters

构造函数返回类型为参数类型的数组

declare function f1(arg: { a: number, b: string }): void
type T0 = Parameters<() => string>;  // []
type T1 = Parameters<(s: string) => void>;  // [string]
type T2 = Parameters<(<T>(arg: T) => T)>;  // [unknown]
type T4 = Parameters<typeof f1>;  // [{ a: number, b: string }]
type T5 = Parameters<any>;  // unknown[]
type T6 = Parameters<never>;  // never
type T7 = Parameters<string>;  // Error
type T8 = Parameters<Function>;  // Error

ConstructorParameters

提取所有参数类型,构成返回,是Parameters的进阶

type T0 = ConstructorParameters<ErrorConstructor>;  // [(string | undefined)?]
type T1 = ConstructorParameters<FunctionConstructor>;  // string[]
type T2 = ConstructorParameters<RegExpConstructor>;  // [string, (string | undefined)?]

ReturnType

构造一个由函数的返回类型组成的类型T

declare function f1(): { a: number, b: string }
type T0 = ReturnType<() => string>;  // string
type T1 = ReturnType<(s: string) => void>;  // void
type T2 = ReturnType<(<T>() => T)>;  // {}
type T3 = ReturnType<(<T extends U, U extends number[]>() => T)>;  // number[]
type T4 = ReturnType<typeof f1>;  // { a: number, b: string }
type T5 = ReturnType<any>;  // any
type T6 = ReturnType<never>;  // any
type T7 = ReturnType<string>;  // Error
type T8 = ReturnType<Function>;  // Error

InstanceType

构造一个和实例类型一样的接口

class C {
    x = 0;
    y = 0;
}

type T0 = InstanceType<typeof C>;  // C {x:number,y:number}
type T1 = InstanceType<any>;  // any
type T2 = InstanceType<never>;  // any
type T3 = InstanceType<string>;  // Error
type T4 = InstanceType<Function>;  // Error

Required

将类型里的可选全部去掉,与Partial相反

interface Props {
    a?: number;
    b?: string;
};

const obj: Props = { a: 5 }; // OK

const obj2: Required<Props> = { a: 5 }; // Error: property 'b' missing