实用工具类型

TypeScript 提供了几种实用程序类型来促进常见的类型转换。这些实用程序在全局作用域内可用。

Awaited<Type>

这种类型旨在模拟 async 函数中的 await 之类的操作,或 Promise 上的 .then() 方法 - 特别是它们递归解包 Promise 的方式。

示例

type A = Awaited<Promise<string>>;

type B = Awaited<Promise<Promise<number>>>;

type C = Awaited<boolean | Promise<number>>;

Partial<Type>

构造一个将 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<Type>

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

示例

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

const obj: Props = { a: 5 };

const obj2: Required<Props> = { a: 5 };

Readonly<Type>

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

示例

interface Todo {
  title: string;
}

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

todo.title = "Hello";

KydTGbCHeFt1bYeUv43GFiGlxeueQcxTOXE1HRextcm5Hbn3j26D0GPBc7IWRo39VkQUjBkloISWVtez4F02EpIOx6uhVF7myDroAzxVxA64Kbu30qNEbBs7bBTWSgRfdCMhEIKEtxIAN5E42vS8P49GYLuvVnd+FZLYQK8HjxRM/AL4IWVTodn1ltKh6YCG8qwOweKAKp9HC5P561cPziocMZToNBiM+tluoXTItKp6fKF5u50YbQd1RJ26gbIi

Object.freeze

function freeze<Type>(obj: Type): Readonly<Type>;

Record<Keys, Type>

mgZv0hzjsNreGsScIny41g9A9wBjAxz5fYCQPpL8fniuI6SfHTV4rslyXz1j3VIkAmeHftjrQRHxjo5QY6Gla80HlDAcRimEptRNMhAeR9wjLNKZ0+kJzXoDwWG1KsLR9kaYqB1l+qjkl4sBFf7t987fjvKnbUcCNg0P8W26kIGOefbeV/Yt0M+P2wjGW5imcv5aITZOqBLku4HopJA/1LvIJh/pC+o9gS02X9QGkak=

示例

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>

UIJpwKLrpOHR2nZCJyo9ig/Uq478kVdhD6fPAThrQ/WYcxk5LghFAXMWH6NaXK1zTQoqiqPQt3OR7F5dPbtE+4uYrKzxB0xPES54jWPpXPh94Mqu5XwUEaad+2skm/Au5I+DYnHSYkOIxSZVCy0neW8c9RyOsspu+8dKoRwuZR6BxgaqWk631p0aBQiJIX5T

示例

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>

UIJpwKLrpOHR2nZCJyo9ig/Uq478kVdhD6fPAThrQ/VXT6143aqeBMXRZJ/WyvsvgtcV69iwKClkCJQUBHXlYHJ27FokIsCO7pj6nZn325xKDSZcPKN4tPpMriEJpV+jG7XONM60drvccgMnZyiRlKIAGCv/g+tjjJSWnWk+MpIRwppjIpImqdyrwnQ1ADU2rcvMknDRhlQhWuwEr9C5FQ==

示例

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>

UIJpwKLrpOHR2nZCJyo9inxmOQxAjVncJc0e3bxiTPFxzUYngy1pr/oFKe/Q0CnBG7yLQkJnnsqNdbqzhIxNThUUmguG0GbWm1HCmH6c+oJOBSOq1zBaSPSpv1VldzGjUh/6OPr3Zxu9hz8F04P8iVF0nhYhEGH7nU0IGAwvLTJKHWZ7mqhT2jl67PoBptP/

示例

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

Extract<Type, Union>

UIJpwKLrpOHR2nZCJyo9imFr2LWRdLwqnWQPWEKOqAmRujuzj1vgHeJW6b+ijl2y++Baer7lYc6OWGhnI0fJV+DQH3768oqJcrpofqQbvDbUe7o/WDS20n2BBt8rItDwUcmj4nwiYX+qG2wzFJGCSk5ppR60goUoxXkBBDfwGMU=

示例

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

NonNullable<Type>

UIJpwKLrpOHR2nZCJyo9imFr2LWRdLwqnWQPWEKOqAkfgyL85czUt8HPT801avb0zFpZRyxfq6EmGKlhr4ug0YdQ9VCfBRjfcB7dtLmcp9NlTIAvD2zX0Ji7vnc9fD6wTgN/1v8/bxArnkJzSytaHw==

示例

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

Parameters<Type>

sR0GW9jwOxv0AqosnDToKgFGIvTlwJsR38cm7CWgvYUvw9IQxY2pQeKjtMv9EfAtD5kMGmDYJsvD6Z0U1paOyfapHF1mlLJ/BQhW2kB5dxeKXa3DKFZIt9YPtFD9YXBj

示例

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

type T0 = Parameters<() => string>;
type T1 = Parameters<(s: string) => void>;
type T2 = Parameters<<T>(arg: T) => T>;
type T3 = Parameters<typeof f1>;
type T4 = Parameters<any>;
type T5 = Parameters<never>;
type T6 = Parameters<string>;
type T7 = Parameters<Function>;

ConstructorParameters<Type>

rY3jqeZnq7FWMzEI4rSeHcIc9SXs/s+i3J0deXF4Oq6Ah1j6kUz3DjfJwS8e1/xdqIXC7pmdDZ3TFWkswrY3K8x1J3xw9tI3vgOaG4FJaMjzEilZOyWkOMaDfHR3VnphRJ8KKlZwiuMO/IoL1iiw304wdc9AbEe1ATCEgaM5WH8lTAB2rrxN7g9WiAkbgyBJvt43EP5yUIKTvpH1BdVinj962UPVmD0v7MJ5Kj3cLdJbRFBzIeGGSX/YGNu8Il+ZYhuxU+8fdOaYsH9T11RiDQ==

示例

type T0 = ConstructorParameters<ErrorConstructor>;
type T1 = ConstructorParameters<FunctionConstructor>;
type T2 = ConstructorParameters<RegExpConstructor>;
type T3 = ConstructorParameters<any>;

type T4 = ConstructorParameters<Function>;

ReturnType<Type>

ReZpG/tFXjv8EEFDtQYoFDL9xCgvmx+PFHHw2c19nuAruN8Fl0HdHBvGxj7jVJVZZ+YYdLki71nAAiVFfBA/Nm5d4pB1oNWNA9Nr2hUODDE=

示例

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

type T0 = ReturnType<() => string>;
type T1 = ReturnType<(s: string) => void>;
type T2 = ReturnType<<T>() => T>;
type T3 = ReturnType<<T extends U, U extends number[]>() => T>;
type T4 = ReturnType<typeof f1>;
type T5 = ReturnType<any>;
type T6 = ReturnType<never>;
type T7 = ReturnType<string>;
type T8 = ReturnType<Function>;

InstanceType<Type>

GaqvKBwpM+AUSopy5a51mrNGpqI4lcpTl1bjd8tJdW9kFRRWtfgIiO2pzj6zvSsESoGTX2M4xoxBW+K6zLmC3+sc8pjpSbwPBEooTxQqkFVLUvmqHD/QC069myNmh3Ph

示例

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

type T0 = InstanceType<typeof C>;
type T1 = InstanceType<any>;
type T2 = InstanceType<never>;
type T3 = InstanceType<string>;
type T4 = InstanceType<Function>;

ThisParameterType<Type>

ZZ95+L/VhWD2SL6WkT1Jg+igmGPAT7A/cIxRVKaQev8D/p3LQyUd+8h81LozThwaOupFqTobBvBQc8CnxnUhukWyABjesYGH/9qOZu+91tHRz9KNUsLvxUAsDkd154J4hWobrm/VrYR6SDmFyBOr/TH/frjkUZ4h/s2fAEnKX/HyoAQWcozXXGi3Q5v3XMjRcOF661cHsr2E4Lko/tI6JByVfe0lrzFj8/5AsD6v4SUh3cyG87RtKLEJBp6NJU6DPfp4Kb4O39bIy1u01NS/7My1H5wrKPnWOUg+MQuHnp0=

示例

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

function numberToString(n: ThisParameterType<typeof toHex>) {
  return toHex.apply(n);
}

OmitThisParameter<Type>

AKNWzv4sK5RUQUpq7wQLhWTG5OeeCJ4nYt7tklUkasV8INp0hsNrdLKlkSJCCglyjAQaCItSQZdPOhi9z6MZMiyhCtW8lTYO3wNjZQMCtk0rBY+8lPUaVzNr+eaVPRFRPQKUfWRCRD7nak3P0yPmh6nvvy35cJYQV6CKCDaqixK05/ye+CQeCfh8f972GuIx6I1PrQqZR511zGFmro55NHZTFEecozN6B1+aIDv2t09q2SurS8T4Mgf5EvhIgKKOZCug9uE3LOHOiV9Bb5E/69ePqtyli2GlW2XMouMJYK+FxoG9lCHSOk+4u6098P5BWPvKS250SIfeW4q5wBTdtwrBDcd9snUNTPMppKOdrXP400WKIJl7cdHa4SXb4Uvck5Eq6Hqouw7ncyj4OaYL72ULi2vc6AhcOZGEleo4rh9ACdIJhZnVatbiSpDNx+XC5JhKJGvhFEZiWRNZFauuxkKo3NplcuU9w65EYGPj4DgczgQqWdHoPhgDqsILVXwu+IgAb15f0hYXQ3VkZRNJi2Lz7F9ZSqfuOkmp/YecWfQ=

示例

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

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

console.log(fiveToHex());

ThisType<Type>

sfhpX7gmSKej17HlBdSGg+pDCYKHyzNUm/+/JQwgFYiNF/F0BHiq2LcOomtByMrMVIDn8YGpIfmqKijNiGsaIx8Luo7Pnx5ccdluUub6PAJVdNd7Mauj80Vt0Efxy5G2nYxDC5JiMvoX6ZCSy3fytCAgd8nSIGiMv8l2czfvlVQfOLygPmVGCZ12Yx4V5sFD9ZA7q8nQA3DkqyJN/sdaeINPTheyTTUv0eenWOrOdbNCzWoanv0PsgKBRTN/XEM633Lw8w6LffYztOwbDMrgVhK57gRAfFYfxOI46RrsWwH4cRRbhleDvcoYbNZtDfpH6tceyOhiO79j7aIYkL8mi4LKTe6KuUBBGIbSsOJ3vOtrN4lPJ7+rfJbixZbEf+U0/pQAxZeVMElD7SA0qBBWxg==

示例

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

NJFONioLQOHSkWKBBUz9BP2lhp1qSAFAAs/4SbHAS7T1Y1QNN2mJeKZB2C1Hiq70wKaVFmDep1C61niGFuryh+7cxsMrW8sl9hhBodgdObC/Z27RE8z3uUsIYeSr35Exy85Ak6bLLqAhDEb0DY/aYQDbz1VGk2+YsVe1mgECXCsWsxX4nLit7TuZv03pPIi7uNTYXuzDrHFwzCSpYrzHebipHF0zo3UrU/s50NGoKue0NVXWTNDRRZHVDu7SsQOz2b5rhfwTRKLLflrXelVYckm4B7uZhJKpK3bxPrcAuDrEQeHcpvuQmWX/pLvBcACXlmnbYesPhpp9wUTOHBH4acqcvEKylYFsmB7x9nRYqLAA6cMe+gJ3+pn2yxq9OB+b1Bhm4iATiQQh5igNXN+8NWsYh2n1lMSZQJVRheYo64W19BcWJV6bDO2ujelvtKcRDlxIHFMkxmnj1Aipv1N8rvYO11zntz7D5cDUcBImRoEe1PrJWrJNSb5bWgkv5STNfJW79AXI5wlz8/CxU4Tv95cQ8R7JB3KLzyyX1dPy0sZ8XbwsCOSoU1DHQaRnumlya2wzJkzCbGU3x5qn1bVdU1PZ5XlQVVL+MZQZvTDbkJX3L5+q2mg4vPUxXOu9Cw2wkgG2WSJRbSP0WcVObd3dSg==

7+ULiQwiFa4GXSVJeJEfEXDVZX2eHgHn2i6qAmKW3dd2ie23MzoCCrjT8w6YKpae3wHoJoHmr8T6lMyOvxRj23emMLbVQ3rsQhDxrMBNuCKfoz6xF1lLljPbkEUfI2bUBetdToZ/8a1xDhrKr0HWA9mRJVkA1Og592vEH0Zl1uDDT2n1x2fqYIZuiFb9dnA8wgruAoG659ib8F5QSa0hWt+Dz8RN0YKiMOih5aADCpXx4g6KOeIybyouxExr5WqNkjA7rrLgmycv1iiqwpRaVQ==

内在字符串操作类型

Uppercase<StringType>

Lowercase<StringType>

Capitalize<StringType>

Uncapitalize<StringType>

H/TBL+uyhGWUAQT4tYjTwHKz3hcgZqS1cHXxwrA5EssfTAg/drZLQOyPkCQxzzVEDGnF+xfgzmH0yXaFOurc74PMwE4zd/H00/nyrq4Hns1nA+xkNnDTQ76/niPyToqkpLyiXENK2ccGj0XM/bDpigpsHTLWBqZa8ee18Lfjytj7lygacQcubkJw5GiupLfBQ35z2JAFYiPfHQnRagMXB3fUUz8nCLzpPAPyGdZi+L/XhOJW5GVf0TS8gZBXvYQc49EM5/4Tq7jesjLKFhHyhEqvxAFc23NO9GOv3rH0fvbfaXqeKGYJn4XCKUFXUSWKpYXBAxYl1y8gIbnicHM9lQ==