百科狗-知识改变命运!
--

工具类型 - TypeScript 类的类型

乐乐1年前 (2023-11-21)阅读数 51#技术干货
文章标签类型

工具类型

Typescript 提供了一些工具,来辅助进行常见的类型转换。这些类型全局可用。

Awaited

此类型用于对async异步函数中的await上,或应用于Promise递归展开.then()方法上。

type A = Awaited;
// type A = string
 
type B = Awaited;
// type B = number
 
type C = Awaited;
// type C = number | boolean


Partial

用于构造一个类型,类型的所有属性都设置为可选。这个工具返回代表给定类型的所有子集的类型。

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

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

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

const todo2 = updateTodo(todo1, {
  description: "throw out trash",
  // description?: string | underfined
});

/*
const todo2: {
  title: string;
  description: string;
}
*/


Required

用于构造一个类型,类型的所有属性都设置为必填的类型。这个工具类型跟Partial相反。

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

const obj: Props = { a: 5 };
const obj2: Required = { a: 5 };
// TypeError: Property 'b' is missing in type '{ a: number; }' but required in type 'Required'.


Readonly

用于构造一个类型,类型的所有属性都设置为readonly的类型。意味着这个类型的所有的属性全都不可以重新赋值。

interface Todo {
  title: string;
}

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

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

这个工具类型用于表示在运行时失败的赋值表达式(即尝试重新分配冻结对象的属性时)。

Object.freeze
function freeze(obj: Type): Readonly;


Record

用于构造一个对象类型,它所有的键都是Keys类型,它所有的值都是Type类型。这个工具类型可以被用于映射一个类型的属性到另一个类型。

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

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

const cats: Record = {
  miffy: { age: 10, breed: "Persian" },
  // (property) miffy: CatInfo
  boris: { age: 5, breed: "Maine Coon" },
  // (property) boris: CatInfo
  mordred: { age: 16, breed: "British Shorthair" },
  // (property) mordred: CatInfo
};
// const cats: Record


Pick

用于构造一个类型,它是从Type类型里面,挑选出属性Keys(Keys是字符串字面量或者字符串字面量的联合类型)

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

type TodoPreview = Pick;
/*
type TodoPreview = {
  title: string;
  completed: boolean;
}
*/

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

todo;
// const todo: TodoPreview


Omit

用于构造一个类型,它是从Type类型里面,过滤掉属性Keys(Keys 是字符串字面量或者字符串字面量的联合类型)

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

type TodoPreview = Omit;
/*
type TodoPreview ={
  title: string;
  completed: boolean;
  createdAt: number;
}
*/

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

todo;
// const todo: TodoPreview


type TodoInfo = Omit;
/*
type TodoInfo = {
  title: string;
  description: string;
}
*/

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

todoInfo;
// const todoInfo: TodoInfo


Exclude

工具类型 - TypeScript 类的类型

用于构造一个类型,它是从UnionType联合类型里面,排除所有ExcludedMembers类型。

type T0 = Exclude;
// type T0 = "b" | "c"

type T1 = Exclude;
// type T1 = "c"

type T2 = Exclude void), Function>;
// type T2 = string | number


Extract

用于构造一个类型,它是从Type类型里面,提取所有Union类型。

type T0 = Extract;
// type T0 = "a"

type T1 = Extract void), Function>;
// type T1 = () => void


NonNullable

用于构造一个类型,从Type中,排除所有的nullundefined类型。

type T0 = NonNullable;
// type T0 = string | number

type T1 = NonNullable;
// type T1 = string[]


Parameters

根据所有Type中,函数的参数类型,构造一个元组类型。

type T0 = Parameters string>;
// type T0 = []

type T1 = Parameters void>;
// type T1 = [s: string]

type T2 = Parameters T>;
// type T2 = [arg: unknown]
declare function f1(arg: { a: number; b: string }): void;
type T3 = Parameters;
/*
type T3 = [arg: {
   a: number;
   b: string;
}]
*/

type T4 = Parameters;
// type T4 = unknown[]

type T5 = Parameters;
// type T5 = never

type T6 = Parameters;
// TypeError: Type 'string' does not satisfy the constraint '(...args: any) => any'.// type T6 = never

type T7 = Parameters;
// TypeError: Type 'Function' does not satisfy the constraint '(...args: any) => any'. Type 'Function' provides no match for the signature '(...args: any): any'.// type T7 = never


ConstructorParameters

根据Type中,构造函数类型,来构造一个元组或数组类型。它产生一个带着所有参数类型的元组。如果Type不是一个函数,则返回never

在 TypeScript 标准库中,内置有构造签名的实际构造函数:interface ErrorConstructorinterface FunctionConstructorinterface RegExpConstructor类型。

type T0 = ConstructorParameters;
// type T0 = [message?: string]

type T1 = ConstructorParameters;
// type T1 = string[]

type T2 = ConstructorParameters;
// type T2 = [pattern: string | RegExp, flags?: string]

type T3 = ConstructorParameters;
// type T3 = unknown[]

type T4 = ConstructorParameters;
// TypeError: Type 'Function' does not satisfy the constraint 'abstract new (...args: any) => any'. Type 'Function' provides no match for the signature 'new (...args: any): any'.// type T4 = never


ReturnType

用于构造一个由Type中函数的返回值的类型,组成的类型。

type T0 = ReturnType string>;
// type T0 = string

type T1 = ReturnType void>;
// type T1 = void

type T2 = ReturnType T>;
// type T2 = unknown

type T3 = ReturnType T>;
// type T3 = number[]
declare function f1(): { a: number; b: string };

type T4 = ReturnType;
/*
type T4 = {
   a: number;
   b: string;
}
*/

type T5 = ReturnType;
// type T5 = any

type T6 = ReturnType;
// type T6 = never

type T7 = ReturnType;
// TypeError: Type 'string' does not satisfy the constraint '(...args: any) => any'.// type T7 = any

type T8 = ReturnType;
// TypeError: Type 'Function' does not satisfy the constraint '(...args: any) => any'. Type 'Function' provides no match for the signature '(...args: any): any'.// type T8 = any


InstanceType

用于构造一个由所有Type中构造函数的实例类型,组成的类型。

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

type T0 = InstanceType;
// type T0 = C

type T1 = InstanceType;
// type T1 = any

type T2 = InstanceType;
// type T2 = never

type T3 = InstanceType;
// TypeError: Type 'string' does not satisfy the constraint 'abstract new (...args: any) => any'.// type T3 = any

type T4 = InstanceType;
// TypeError: Type 'Function' does not satisfy the constraint 'abstract new (...args: any) => any'. Type 'Function' provides no match for the signature 'new (...args: any): any'.// type T4 = any


ThisParameterType

用于提取函数的this参数的类型。如果这个函数没有this参数,则返回unknown类型。

function toHex(this: Number) {
  return this.toString(16);
}

function numberToString(n: ThisParameterType) {
  return toHex.apply(n);
  // (parameter) n: number
}


OmitThisParameter

用于移除函数的this参数的类型。如果Type没有明确的声明this类型,那么这个返回的结果就是Type,不然的话,就返回一个新的函数类型,基于Type,但不再有this参数。泛型会被抹去,只有最后重载的签名被传播进了返回的新的函数类型。

function toHex(this: Number) {
 return this.toString(16);
}

const fiveToHex: OmitThisParameter = toHex.bind(5);

console.log(fiveToHex());


ThisType

这个类型不返回一个转换过的类型,它被用作标记一个上下文的this类型。注意:如果想使用这个工具类型,noImplicitThis选项,必须启用。

type ObjectDescriptor = {
  data?: D;
  methods?: M & ThisType; // Type of 'this' in methods is D & M
};

function makeObject(desc: ObjectDescriptor): D & M {
  let data: object = desc.data || {};
  let methods: object = desc.methods || {};
  return { ...data, ...methods } as D & M;
}

let obj = makeObject({
  data: { x: 0, y: 0 },
  methods: {
    moveBy(dx: number, dy: number) {
      this.x += dx; // Strongly typed this
      this.y += dy; // Strongly typed this
    },
  },
});

obj.x = 10;
obj.y = 20;
obj.moveBy(5, 5);

在上面的例子中,makeObject函数的参数重methods对象有上下文的类型包含了ThisType,因此methods方法中的this类型是{x: number, y: number}&{moveBy(dx: number, dy: number): number}。注意methods的类型是怎么同时成为一个接口的目标和方法中this类型的源。

ThisType标记的接口是一个生命在lib.d.ts中的简单的空接口。除了被认为是一个对象字面量的上下文类型,这个接口表现得就像一个空接口。


内置字符操作类型

  • Uppercase
  • Lowercase
  • Capitalize
  • Uncapitalize

为了帮助围绕模版字符串的字符串处理,TypeScript 的类型系统包含了一系列中可以用于字符串操作的类型。你可以在文档模板字面量类型中找到这些。

鹏仔微信 15129739599 鹏仔QQ344225443 鹏仔前端 pjxi.com 共享博客 sharedbk.com

免责声明:我们致力于保护作者版权,注重分享,当前被刊用文章因无法核实真实出处,未能及时与作者取得联系,或有版权异议的,请联系管理员,我们会立即处理! 部分文章是来自自研大数据AI进行生成,内容摘自(百度百科,百度知道,头条百科,中国民法典,刑法,牛津词典,新华词典,汉语词典,国家院校,科普平台)等数据,内容仅供学习参考,不准确地方联系删除处理!邮箱:344225443@qq.com)

图片声明:本站部分配图来自网络。本站只作为美观性配图使用,无任何非法侵犯第三方意图,一切解释权归图片著作权方,本站不承担任何责任。如有恶意碰瓷者,必当奉陪到底严惩不贷!

内容声明:本文中引用的各种信息及资料(包括但不限于文字、数据、图表及超链接等)均来源于该信息及资料的相关主体(包括但不限于公司、媒体、协会等机构)的官方网站或公开发表的信息。部分内容参考包括:(百度百科,百度知道,头条百科,中国民法典,刑法,牛津词典,新华词典,汉语词典,国家院校,科普平台)等数据,内容仅供参考使用,不准确地方联系删除处理!本站为非盈利性质站点,本着为中国教育事业出一份力,发布内容不收取任何费用也不接任何广告!)