10. TS 类型计算入门(描述类型的小工具)

描述类型的小工具

观察所有Typescritp提供的类型下小工具,思考这个问题: - 类型是可以被计算的吗? 内容:
- Partial\<Type\>
- Required\<Type\>
- Readonly\<Type\>
- Record\<Keys,Type\>
- Pick\<Type, Keys\>
- Omit\<Type, Keys\>
- Exclude\<Type, ExcludedUnion\>
- Extract\<Type, Union\>
- NonNullable\<Type\>
- Parameters\<Type\>
- ConstructorParameters\<Type\>
- ReturnType\<Type\>
- InstanceType\<Type\>
- ThisParameterType\<Type\>
- OmitThisParameter\<Type\>
- ThisType\<Type\>
- Intrinsic String Manipulation Types
- Uppercase\<StringType\>
- Lowercase\<StringType\>
- Capitalize\<StringType\>
- Uncapitalize\<StringType\>

Keyof 操作符

type Point = { x: number; y: number };
type P = keyof Point;
// type P = "x" | "y"

type Arrayish = { [n: number]: unknown };
type A = keyof Arrayish;
// type A = number

type Mapish = { [k: string]: boolean };
type M = keyof Mapish;
// type M = string | number

Typeof

console.log(typeof "xxx") // string

let s = "hello"
let n : typeof s
// n -- string

Partial Type

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

function updateTodo(todo: Todo, fieldsToUpdate: Partial<Todo>) {
  return { ...todo, ...fieldsToUpdate };
}

const todo1 = {
  title: "organize desk",
  description: "clear clutter",
};

const todo2 = updateTodo(todo1, {
  description: "throw out trash",
});

Source Code of Partial

type Partial<T> = {
    [P in keyof T]?: T[P];
}

Required

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

const obj: Props = { a: 5 };

const obj2: Required<Props> = { a: 5 };
// Error : Property 'b' is missing in type '{ a: number; }' but required in type 'Required<Props>'

Source Code of Required

type Required<T> = {
    [P in keyof T]-?: T[P];
};

Readonly

interface Todo {
  title: string;
}

const todo: Readonly<Todo> = {
  title: "Delete inactive users",
};

todo.title = "Hello";
// Error : Cannot assign to 'title' because it is a read-only property.

Source Code of Readonly

type Readonly<T> = {
    readonly [P in keyof T]: T[P];
};

Record

interface CatInfo {
  age: number;
  breed: string;
}

type CatName = "miffy" | "boris" | "mordred";

const cats: Record<CatName, CatInfo> = {
  miffy: { age: 10, breed: "Persian" },
  boris: { age: 5, breed: "Maine Coon" },
  mordred: { age: 16, breed: "British Shorthair" },
};

cats.boris;

Source Code of Record

type Record<K extends keyof any, T> = {
    [P in K]: T;
};

Pick

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

type TodoPreview = Pick<Todo, "title" | "completed">;

const todo: TodoPreview = {
  title: "Clean room",
  completed: false,
};

todo;

Source Code of Pick

type Pick<T, K extends keyof T> = {
    [P in K]: T[P];
};

Exclude

type T0 = Exclude<"a" | "b" | "c", "a">;

// type T0 = "b" | "c"
type T1 = Exclude<"a" | "b" | "c", "a" | "b">;

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

// type T2 = string | number

Source Code of Exclude

type Exclude<T, U> = T extends U ? never : T;

Omit

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

type TodoPreview = Omit<Todo, "description">;

const todo: TodoPreview = {
  title: "Clean room",
  completed: false,
  createdAt: 1615544252770,
};

todo;

type TodoInfo = Omit<Todo, "completed" | "createdAt">;

const todoInfo: TodoInfo = {
  title: "Pick up kids",
  description: "Kindergarten closes at 5pm",
};

todoInfo;

Source Code of Omit

type Omit<T, K extends keyof any> = Pick<T, Exclude<keyof T, K>>

Extract

type T0 = Extract<"a" | "b" | "c", "a" | "f">;

// type T0 = "a"
type T1 = Extract<string | number | (() => void), Function>;

// type T1 = () => void

Source Code of Extract

type Extract<T, U> = T extends U ? T : never;

NonNullable

type T0 = NonNullable<string | number | undefined>;

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

// type T1 = string[]

Source Code of NonNullable

type NonNullable<T> = T extends null | undefined ? never : T;

Parameters

declare function f1(arg: { a: number; b: string }): void;

type T0 = Parameters<() => string>;

//type T0 = []
type T1 = Parameters<(s: string) => void>;

//type T1 = [s: string]
type T2 = Parameters<<T>(arg: T) => T>;

//type T2 = [arg: unknown]

//type T3 = [arg: {
//    a: number;
//    b: string;
//}]

错误构造函数接口定义

/**
 * ErrorConstructor定义了Error类的构造函数类型。
 */
interface ErrorConstructor {
    // 构造一个新的Error对象
    new(message?: string): Error;
    // 通过函数方式创建Error对象
    (message?: string): Error;
    // Error的原型对象
    readonly prototype: Error;
}

函数构造函数接口定义

/**
 * FunctionConstructor定义了Function类的构造函数类型。
 */
interface FunctionConstructor {
    /**
     * 创建一个新的函数。
     * @param args 函数接受的参数列表。
     */
    new(...args: string[]): Function;
    // 通过函数方式创建Function对象
    (...args: string[]): Function;
    // Function的原型对象
    readonly prototype: Function;
}

正则表达式构造函数接口定义

/**
 * RegExpConstructor定义了RegExp类的构造函数类型。
 */
interface RegExpConstructor {
    // 根据给定的正则表达式或字符串构造一个新的RegExp对象
    new(pattern: RegExp | string): RegExp;
    // 根据给定的字符串和标志构造一个新的RegExp对象
    new(pattern: string, flags?: string): RegExp;
    // 通过函数方式创建RegExp对象
    (pattern: RegExp | string): RegExp;
    // 通过函数方式创建RegExp对象并传入标志
    (pattern: string, flags?: string): RegExp;
    // RegExp的原型对象
    readonly prototype: RegExp;

    // 非标准扩展属性
    $1: string;
    $2: string;
    $3: string;
    $4: string;
    $5: string;
    $6: string;
    $7: string;
    $8: string;
    $9: string;
    lastMatch: string;
}
注意:在上述代码中,有一些非标准的扩展属性(如`$1`,`$2`等),这些属性在某些实现中可能存在,但并不是所有JavaScript环境都支持。

源码如何实现?

// 在TypeScript中,您可以使用typeof关键字来获取变量或对象的类型。
type Parameters<T extends (...args: any) => any> = T extends (...args: infer P) => any ? P : never;

ConstructorParameters

// ConstructorParameters类型用于获得类构造函数或普通函数的参数类型组成的元组。
type ConstructorParameters<T extends abstract new (...args: any) => any> = T extends abstract new (...args: infer P) => any ? P : never;

ReturnType

// ReturnType类型用于获取函数的返回类型。
type ReturnType<T extends (...args: any) => any> = T extends (...args: any) => infer R ? R : any;

InstanceType

// InstanceType类型用于获取类的实例类型。
type InstanceType<T extends abstract new (...args: any) => any> = T extends abstract new (...args: any) => infer R ? R : any;

ThisParameterType

// ThisParameterType类型用于获取函数中this的类型。
type ThisParameterType<T> = T extends (this: infer U, ...args: any[]) => any ? U : unknown;

OmitThisParameter

// OmitThisParameter类型用于从函数参数中删除this。
type OmitThisParameter<T> = unknown extends ThisParameterType<T> ? T : T extends (...args: infer A) => infer R ? (...args: A) => R : T;

ThisType

// ThisType用于提供一个接口中方法的this类型。但实际的实现是空的,它依赖于编译器来解释。
interface ThisType<T> { }

Uppercase / Lowercase

// 这些内建的字符串操作类型用于修改字符串类型的大小写。
// 这些类型内部是如何实现的不是公开的,因为它们是编译器的内部实现。
type Uppercase<S extends string> = intrinsic;
type Lowercase<S extends string> = intrinsic;
type Capitalize<S extends string> = intrinsic;
type Uncapitalize<S extends string> = intrinsic;

总结

- 在TypeScript中,类型是可以进行计算和操作的。
- 通过使用 & 和 |,我们可以创建交集和联合类型。
- 通过使用 -,我们可以从联合类型中排除某些类型。
- 通过使用 ?,我们可以使对象的属性变为可选。
- 使用 infer 关键字在条件类型中进行类型推断。
- 使用 ... 进行类型的展开和收缩。
**注意**:对于某些内建的类型,例如`Uppercase`和`Lowercase`,它们的实际实现不是公开的,因为它们是编译器的内部实现。在文档中,这些类型通常被标记为`intrinsic`,意味着它们的行为是内置的,并且不依赖于外部的类型定义。

posted on 2022-03-08 18:52  完美前端  阅读(148)  评论(0)    收藏  举报

导航