【TypeScript】 ts内置定义的类型

简言

typescript中内置了一部分类型来简化、快速定义类型。
TypeScript 提供了多种实用程序类型,以促进常见的类型转换。这些实用程序可在全局范围内使用。

内置类型

下面尖括号的常用参数描述:

  • Type —— 表示一个类型参数,根据内置类型改变
  • Keys —— 表示一个key集合,一般是字符串联合类型或字符串,要符合 keyof Type 。

Awaited 异步结果

该类型旨在模拟异步函数中的 await 或 Promises 上的 .then() 方法等操作,代表异步之后返回的结果类型。
例如:

//	A - string
type A = Awaited<Promise<string>>;
//	B - number
type B = Awaited<Promise<Promise<number>>>;
//	C - boolean | number
type C = Awaited<boolean | Promise<number>>;

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",
});

Required 必选

与 Partial 相反,构造一个由设置为必填的 Type 的所有属性组成的类型。

interface Props {
  a?: number;
  b?: string;
}
 
const obj: Props = { a: 5 };
// error
const obj2: Required<Props> = { a: 5 };

Readonly 只读

构造一个 Type 的所有属性都设置为只读的类型,这意味着构造的类型的属性不能被重新分配。

interface Todo {
  title: string;
}
 
const todo: Readonly<Todo> = {
  title: "Delete inactive users",
};
 // error
todo.title = "Hello";

Record<Keys, Type> 映射对象类型

构造一个属性键为 Keys、属性值为 Type 的对象类型。该工具可用于将一个类型的属性映射到另一个类型。

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;

Pick<Type, Keys> 选取新建

从类型中选取属性键集(字符串字面量或字符串字面量的组合),构建类型。

interface Todo {
  title: string;
  description: string;
  completed: boolean;
}
 
type TodoPreview = Pick<Todo, "title" | "completed">;
 
const todo: TodoPreview = {
  title: "Clean room",
  completed: false,
};
 
todo;

Omit<Type, Keys> 选取删除

从 Type 中选取所有属性,然后删除键(字符串字面量或字符串字面量的联合),从而构造一个类型。与 Pick 相反。

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;

Exclude<UnionType, ExcludedMembers> 排除

通过从 UnionType(元组) 中排除所有可赋值给 ExcludedMembers 的联盟成员来构建类型。

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

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

type Shape =
  | { kind: "circle"; radius: number }
  | { kind: "square"; x: number }
  | { kind: "triangle"; x: number; y: number };
 //	 { kind: "square"; x: number }
 // | { kind: "triangle"; x: number; y: number };
type T3 = Exclude<Shape, { kind: "circle" }>

Extract<Type, Union> 提取

从 Type 中提取可赋值给 Union 的所有 union 成员,从而构造一个类型。

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

type Shape =
  | { kind: "circle"; radius: number }
  | { kind: "square"; x: number }
  | { kind: "triangle"; x: number; y: number };
//	 {
//    kind: "circle";
//    radius: number;
// }
type T2 = Extract<Shape, { kind: "circle" }>

NonNullable 非空和非未定义

通过从 Type 中排除 null 和 undefined 来构造一个类型。

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

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

Parameters 提取参数类型

从函数类型 Type 的参数中使用的类型构造一个元组类型。

对于重载函数,这将是最后一个签名的参数;

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

// error
type T6 = Parameters<string>;
// error
type T7 = Parameters<Function>;

ConstructorParameters 提取构造函数类型

根据构造函数类型构造一个元组或数组类型。它会生成一个包含所有参数类型的元组类型(如果 Type 不是函数,则永远不会生成类型)。

//type T0 = [message?: string]
type T0 = ConstructorParameters<ErrorConstructor>;
     
// type T1 = string[]
type T1 = ConstructorParameters<FunctionConstructor>;
     
// type T2 = [pattern: string | RegExp, flags?: string]
type T2 = ConstructorParameters<RegExpConstructor>;
     

class C {
  constructor(a: number, b: string) {}
}

// type T3 = [a: number, b: string]
type T3 = ConstructorParameters<typeof C>;
     
// type T4 = unknown[]
type T4 = ConstructorParameters<any>;
     

// error
type T5 = ConstructorParameters<Function>;

ReturnType 提取返回值类型

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

对于重载函数,这将是最后一个签名的返回类型;

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

InstanceType 创建实例类型

构造一个类型,该类型由 Type 中构造函数的实例类型组成。

class C {
  x = 0;
  y = 0;
  constructor() {

  }
}
//  C
type T0 = InstanceType<typeof C>;
// 
const aa: T0 = new C()
aa.x
aa.y
//  any 
type T1 = InstanceType<any>;
// never
type T2 = InstanceType<never>;

NoInfer 阻止类型推断,且符合Type范围

阻止对所含类型的推断。除阻止推论外,NoInfer 与 Type 相同。

function createStreetLight<C extends string>(
  colors: C[],
  defaultColor?: NoInfer<C>,
) {
  // ...
}
createStreetLight(["red", "yellow", "green"], "red");  // OK
createStreetLight(["red", "yellow", "green"], "blue");  // Error

ThisParameterType 提取this参数类型

提取函数类型的 this 参数类型,如果函数类型没有 this 参数,则提取unknown类型。

function toHex(this: Number) {
  return this.toString(16);
}
 //	n: number
function numberToString(n: ThisParameterType<typeof toHex>) {
  return toHex.apply(n);
}

OmitThisParameter

删除 Type 中的 this 参数。如果 Type 没有显式声明 this 参数,则结果只是 Type。否则,将从 Type 创建一个没有 this 参数的新函数类型。泛型会被删除,只有最后一个重载签名会传播到新函数类型中。

function toHex(this: Number) {
  return this.toString(16);
}
 
const fiveToHex: OmitThisParameter<typeof toHex> = toHex.bind(5);
 
console.log(fiveToHex());

ThisType

此实用程序不会返回转换后的类型。相反,它会作为上下文此类型的标记。请注意,必须启用 noImplicitThis 标记才能使用此工具。

type ObjectDescriptor<D, M> = {
  data?: D;
  methods?: M & ThisType<D & M>; // Type of 'this' in methods is D & M
};
 
function makeObject<D, M>(desc: ObjectDescriptor<D, M>): 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 的参数中的方法对象的上下文类型包括 ThisType<D & M>,因此方法对象中方法的 this 类型是 { x: number, y: number } & { moveBy(dx: number, dy: number): void }。请注意,methods 属性的类型同时是推理目标和方法中 this 类型的来源。

ThisType<T> 标记接口只是 lib.d.ts 中声明的一个空接口。除了在对象字面的上下文类型中被识别外,该接口的行为与任何空接口一样。

Uppercase 字符串大写

将字符串中的每个字符转换为大写字母。

type Greeting = "Hello, world"
//	HELLO, WORLD
type ShoutyGreeting = Uppercase<Greeting>

type ASCIICacheKey<Str extends string> = `ID-${Uppercase<Str>}`
//	ID-MY_APP
type MainID = ASCIICacheKey<"my_app">

Lowercase 字符串小写

将字符串中的每个字符转换为小写字母。

type Greeting = "Hello, world"
//	hello, world
type QuietGreeting = Lowercase<Greeting>

type ASCIICacheKey<Str extends string> = `id-${Lowercase<Str>}`
//	id-my_app
type MainID = ASCIICacheKey<"MY_APP">

Capitalize 首字符大写

将字符串中的第一个字符转换为大写字母。

type LowercaseGreeting = "hello, world";
//	Hello, world
type Greeting = Capitalize<LowercaseGreeting>;

Uncapitalize 首字符小写

将字符串中的第一个字符转换为小写字母。

type UppercaseGreeting = "HELLO WORLD";
//	hELLO WORLD
type UncomfortableGreeting = Uncapitalize<UppercaseGreeting>;

结语

结束了。

  • 22
    点赞
  • 29
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ZSK6

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值