Project Icon

utility-types

TypeScript 实用类型集合 补充内置类型和别名

utility-types 是一个为 TypeScript 项目提供常用类型的开源库。它包含多种实用类型操作符,如 SetIntersection、FunctionKeys 和 DeepPartial 等,补充了 TypeScript 内置类型。该库经过充分测试,无运行时开销,适用于 TypeScript 3.1+ 版本。它可帮助开发者更便捷地处理复杂类型操作,提升代码的类型安全性和可维护性。

utility-types

Collection of utility types, complementing TypeScript built-in mapped types and aliases (think "lodash" for static types).

Latest Stable Version NPM Downloads NPM Downloads Bundlephobia Size

CI Check License Join the community on Spectrum

Found it useful? Want more updates?

Show your support by giving a :star:

Buy Me a Coffee Become a Patron



What's new?

:tada: Added new utilities :tada:



Features

Goals

  • Quality - thoroughly tested for type correctness with type-testing library dts-jest
  • Secure and minimal - no third-party dependencies
  • No runtime cost - it's type-level only

Installation

# NPM
npm install utility-types

# YARN
yarn add utility-types

Compatibility Notes

TypeScript support

  • v3.x.x - TypeScript v3.1+
  • v2.x.x - TypeScript v2.8.1+
  • v1.x.x - TypeScript v2.7.2+

Funding Issues

Utility-Types is an open-source project created by people investing their time for the benefit of our community.

Issues like bug fixes or feature requests can be very quickly resolved when funded through the IssueHunt platform.

I highly recommend adding a bounty to the issue that you're waiting for to attract some contributors willing to work on it.

Let's fund issues in this repository

Contributing

We are open for contributions. If you're planning to contribute please make sure to read the contributing guide as it can save you from wasting your time: CONTRIBUTING.md


  • (built-in) - types built-in TypeScript, no need to import

Table of Contents

Aliases & Type Guards

Union operators

Object operators

Special operators

Flow's Utility Types

Deprecated API (use at own risk)

  • getReturnOfExpression() - from TS v2.0 it's better to use type-level ReturnType instead

Primitive

Type representing primitive types in JavaScript, and thus TypeScript: string | number | bigint | boolean | symbol | null | undefined

You can test for singular of these types with typeof

isPrimitive

This is a TypeScript Typeguard for the Primitive type.

This can be useful to control the type of a parameter as the program flows. Example:

const consumer = (param: Primitive[] | Primitive): string => {
    if (isPrimitive(param)) {
        // typeof param === Primitive
        return String(param) + ' was Primitive';
    }
    // typeof param === Primitive[]
    const resultArray = param
        .map(consumer)
        .map(rootString => '\n\t' + rootString);
    return resultArray.reduce((comm, newV) => comm + newV, 'this was nested:');
};

⇧ back to top

Falsy

Type representing falsy values in TypeScript: false | "" | 0 | null | undefined

Except NaN which cannot be represented as a type literal

isFalsy

const consumer = (param: Falsy | string): string => {
    if (isFalsy(param)) {
        // typeof param === Falsy
        return String(param) + ' was Falsy';
    }
    // typeof param === string
    return param.toString();
};

⇧ back to top

Nullish

Type representing nullish values in TypeScript: null | undefined

⇧ back to top

isNullish

const consumer = (param: Nullish | string): string => {
    if (isNullish(param)) {
        // typeof param === Nullish
        return String(param) + ' was Nullish';
    }
    // typeof param === string
    return param.toString();
};

⇧ back to top

SetIntersection<A, B> (same as Extract)

Set intersection of given union types A and B

Usage:

import { SetIntersection } from 'utility-types';

// Expect: "2" | "3"
type ResultSet = SetIntersection<'1' | '2' | '3', '2' | '3' | '4'>;
// Expect: () => void
type ResultSetMixed = SetIntersection<string | number | (() => void), Function>;

⇧ back to top

SetDifference<A, B> (same as Exclude)

Set difference of given union types A and B

Usage:

import { SetDifference } from 'utility-types';

// Expect: "1"
type ResultSet = SetDifference<'1' | '2' | '3', '2' | '3' | '4'>;
// Expect: string | number
type ResultSetMixed = SetDifference<string | number | (() => void), Function>;

⇧ back to top

SetComplement<A, A1>

Set complement of given union types A and (it's subset) A1

Usage:

import { SetComplement } from 'utility-types';

// Expect: "1"
type ResultSet = SetComplement<'1' | '2' | '3', '2' | '3'>;

⇧ back to top

SymmetricDifference<A, B>

Set difference of union and intersection of given union types A and B

Usage:

import { SymmetricDifference } from 'utility-types';

// Expect: "1" | "4"
type ResultSet = SymmetricDifference<'1' | '2' | '3', '2' | '3' | '4'>;

⇧ back to top

NonNullable<A>

Exclude null and undefined from set A

⇧ back to top

NonUndefined<A>

Exclude undefined from set A

⇧ back to top

Exclude<A, B>

Exclude subset B from set A

⇧ back to top

Extract<A, B>

Extract subset B from set A

⇧ back to top

Operations on objects

FunctionKeys<T>

Get union type of keys that are functions in object type T

Usage:

import { FunctionKeys } from 'utility-types';

type MixedProps = { name: string; setName: (name: string) => void };

// Expect: "setName"
type Keys = FunctionKeys<MixedProps>;

⇧ back to top

NonFunctionKeys<T>

Get union type of keys that are non-functions in object type T

Usage:

import { NonFunctionKeys } from 'utility-types';

type MixedProps = { name: string; setName: (name: string) => void };

// Expect: "name"
type Keys = NonFunctionKeys<MixedProps>;

⇧ back to top

MutableKeys<T>

Get union type of keys that are mutable (not readonly) in object type T

Alias: WritableKeys<T>

Usage:

import { MutableKeys } from 'utility-types';

type Props = { readonly foo: string; bar: number };

// Expect: "bar"
type Keys = MutableKeys<Props>;

⇧ back to top

ReadonlyKeys<T>

Get union type of keys that are readonly in object type T

Usage:

import { ReadonlyKeys } from 'utility-types';

type Props = { readonly foo: string; bar: number };

// Expect: "foo"
type Keys = ReadonlyKeys<Props>;

⇧ back to top

RequiredKeys<T>

Get union type of keys that are required in object type T

Usage:

import { RequiredKeys } from 'utility-types';

type Props = { req: number; reqUndef: number | undefined; opt?: string; optUndef?: number | undefined; };

// Expect: "req" | "reqUndef"
type Keys = RequiredKeys<Props>;

⇧ back to top

OptionalKeys<T>

Get union type of keys that are optional in object type T

Usage:

import { OptionalKeys } from 'utility-types';

type Props = { req: number; reqUndef: number | undefined; opt?: string; optUndef?: number | undefined; };

// Expect: "opt" | "optUndef"
type Keys = OptionalKeys<Props>;

⇧ back to top

UnionKeys<U>

Get keys of all objects in the union type U

Usage:

import { UnionKeys } from 'utility-types';

type Props = { name: string } | { age: number } | { visible: boolean };

// Expect: "name" | "age" | "visible"
type Keys = UnionKeys<Props>;

⇧ back to top

Optional<T, K>

From T make a set of properties by key K become optional

Usage:

import { Optional } from 'utility-types';

type Props = { name: string; age: number; visible: boolean; };

// Expect: { name?: string; age?: number; visible?: boolean; }
type Props = Optional<Props>
// Expect: { name: string; age?: number; visible?: boolean; }
type Props = Optional<Props, 'age' | 'visible'>;

⇧ back to top

Pick<T, K> (built-in)

From T pick a set of properties by key K

Usage:

type Props = { name: string; age: number; visible: boolean };

// Expect: { age: number; }
type Props = Pick<Props, 'age'>;

⇧ back to top

PickByValue<T, ValueType>

From T pick a set of properties by value matching ValueType. (Credit: Piotr Lewandowski)

Usage:

import { PickByValue } from 'utility-types';

type Props = { req: number; reqUndef: number | undefined; opt?: string; };

// Expect: { req: number }
type Props = PickByValue<Props, number>;
// Expect: { req: number; reqUndef: number | undefined; }
type Props = PickByValue<Props, number | undefined>;

⇧ back to top

PickByValueExact<T, ValueType>

From T pick a set of properties by value matching exact ValueType.

Usage:

import { PickByValueExact } from 'utility-types';

type Props = { req: number; reqUndef: number | undefined; opt?: string; };

// Expect: { req: number }
type Props = PickByValueExact<Props, number>;
// Expect: { reqUndef: number | undefined; }
type Props = PickByValueExact<Props, number | undefined>;

⇧ back to top

Omit<T, K>

From T remove a set of properties by key K

Usage:

import { Omit } from 'utility-types';

type Props = { name: string; age: number;
项目侧边栏1项目侧边栏2
推荐项目
Project Cover

豆包MarsCode

豆包 MarsCode 是一款革命性的编程助手,通过AI技术提供代码补全、单测生成、代码解释和智能问答等功能,支持100+编程语言,与主流编辑器无缝集成,显著提升开发效率和代码质量。

Project Cover

AI写歌

Suno AI是一个革命性的AI音乐创作平台,能在短短30秒内帮助用户创作出一首完整的歌曲。无论是寻找创作灵感还是需要快速制作音乐,Suno AI都是音乐爱好者和专业人士的理想选择。

Project Cover

有言AI

有言平台提供一站式AIGC视频创作解决方案,通过智能技术简化视频制作流程。无论是企业宣传还是个人分享,有言都能帮助用户快速、轻松地制作出专业级别的视频内容。

Project Cover

Kimi

Kimi AI助手提供多语言对话支持,能够阅读和理解用户上传的文件内容,解析网页信息,并结合搜索结果为用户提供详尽的答案。无论是日常咨询还是专业问题,Kimi都能以友好、专业的方式提供帮助。

Project Cover

阿里绘蛙

绘蛙是阿里巴巴集团推出的革命性AI电商营销平台。利用尖端人工智能技术,为商家提供一键生成商品图和营销文案的服务,显著提升内容创作效率和营销效果。适用于淘宝、天猫等电商平台,让商品第一时间被种草。

Project Cover

吐司

探索Tensor.Art平台的独特AI模型,免费访问各种图像生成与AI训练工具,从Stable Diffusion等基础模型开始,轻松实现创新图像生成。体验前沿的AI技术,推动个人和企业的创新发展。

Project Cover

SubCat字幕猫

SubCat字幕猫APP是一款创新的视频播放器,它将改变您观看视频的方式!SubCat结合了先进的人工智能技术,为您提供即时视频字幕翻译,无论是本地视频还是网络流媒体,让您轻松享受各种语言的内容。

Project Cover

美间AI

美间AI创意设计平台,利用前沿AI技术,为设计师和营销人员提供一站式设计解决方案。从智能海报到3D效果图,再到文案生成,美间让创意设计更简单、更高效。

Project Cover

AIWritePaper论文写作

AIWritePaper论文写作是一站式AI论文写作辅助工具,简化了选题、文献检索至论文撰写的整个过程。通过简单设定,平台可快速生成高质量论文大纲和全文,配合图表、参考文献等一应俱全,同时提供开题报告和答辩PPT等增值服务,保障数据安全,有效提升写作效率和论文质量。

投诉举报邮箱: service@vectorlightyear.com
@2024 懂AI·鲁ICP备2024100362号-6·鲁公网安备37021002001498号