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];

相关

CSS 清除浮动

2018-05-21

在浮动布局中,有时候会因为父元素没有设置高度而子元素浮动导致父元素坍塌,我们就需要清除浮动撑起父元素的高度,在这里总结一下常用方法。

了解更多

1768年中国妖术大恐慌

2024-12-02

中国近代史的发展历程

了解更多

Linux-基础

2018-10-28

Linux 是在做一些较为底层的开发工作时的必要开发环境,了解 Linux 也对操作系统概念的理解有很大的帮助,这篇文章是对 Linux 的一些基础概念的阐述。

了解更多