ts常用体操

内容列表

这里记录一些常用的类型定义

1.对象属性只读(递归)

type X = {
  x: {
    a: 1;
    b: "hi";
  };
  y: "hey";
};

type Expected = {
  readonly x: {
    readonly a: 1;
    readonly b: "hi";
  };
  readonly y: "hey";
};

type Todo = DeepReadonly<X>; // should be same as `Expected`

// 实现
type DeepReadonly<T> = keyof T extends never
  ? T
  : { readonly [k in keyof T]: DeepReadonly<T[k]> };

2.元组转换为对象

type Tuple = ["tesla", "model 3", "model X", "model Y"]; // ['tesla', 'model 3', 'model X', 'model Y']

type Result = TupleToObject<Tuple>; // expected { tesla: 'tesla'; 'model 3': 'model 3'; 'model X': 'model X'; 'model Y': 'model Y' }

// 实现
type TupleToObject<T extends readonly (string | number)[]> = {
  [K in T[number]]: K;
};

3.获得可选属性

type I = GetOptional<{ foo: number; bar?: string }>; // expected to be { bar?: string }

// 实现
type GetOptional<T> = {
  [P in keyof T as T[P] extends Required<T>[P] ? never : P]: T[P];
};

4.获得必需的属性

type I = GetRequired<{ foo: number; bar?: string }>; // expected to be { foo: number }

// 实现
type GetRequired<T> = {
  [P in keyof T as T[P] extends Required<T>[P] ? P : never]: T[P];
};

5.获取class的公有属性

class A {
  public str: string;
  protected num: number;
  private bool: boolean;
  getNum() {
    return Math.random();
  }
}

type publicKeys = ClassPublicKeys<A>; // 'str' | 'getNum'

// 使用方案
type ClassPublicKeys<A> = keyof A;

6.获取class的私有属性

class A {
  public str: string;
  protected num: number;
  private bool: boolean;
  getNum() {
    return Math.random();
  }
}

type privateKeys = ClassPrivateKeys<A>; // 'bool'

// 使用方案
type ClassPrivateKeys<A> = {
  [K in keyof A]: A[K] extends Function ? never : K;
}[keyof A];

7.获取class的受保护属性

class A {
  public str: string;
  protected num: number;
  private bool: boolean;
  getNum() {
    return Math.random();
  }
}

type protectedKeys = ClassProtectedKeys<A>; // 'num'

// 使用方案
type ClassProtectedKeys<A> = {
  [K in keyof A]: A[K] extends Function ? never : K;
}[keyof A];

相关

原生表格的虚拟滚动实践(上)

2024-12-16

由于业务开发需要在低版本浏览器中使用,所以需要使用原生表格实现虚拟滚动,本篇仅分享表格竖向的虚拟滚动。

了解更多

单元测试工具:Junit

2017-08-30

通常一个项目的代码量是比较大的,而且其中逻辑也较为复杂,在开发完成后再进行项目测试其实是比较耗费时间和精力的,因此边开发边测试是个很好的选择,而 JUnit 则为我们提供了这样的便利。

了解更多

使用 Git

2018-12-31

Git 是一个分布式的版本控制工具,类似的版本控制工具还有 SVN ;由于 GitHub 平台的盛行,也使得 git 更加受欢迎,在 Windows 平台使用 git 也是非常方便的。

了解更多