type-fest README

README проекта с github.com/sindresorhus/type-fest. Одним файлом markdown: README.md.



type-fest

A collection of essential TypeScript types





npm dependents npm downloads

Many of the types here should have been built-in. You can help by suggesting some of them to the TypeScript project.

Either add this package as a dependency or copy-paste the needed types. No credit required. 👌

PR welcome for additional commonly needed types and docs improvements. Read the contributing guidelines first.

Help wanted with reviewing proposals and pull requests.

Install

npm install type-fest

Requires TypeScript >=6, ESM, and {strict: true} in your tsconfig.

{exactOptionalPropertyTypes: true} is required. Disabling it is unsupported.

[!NOTE] This readme shows the current development version. For docs about the latest version, see the npm page.

You may also like my ts-extras package which provides runtime functions for some of these types.

Usage

import type {Except} from 'type-fest';

type Foo = {
	unicorn: string;
	rainbow: boolean;
};

type FooWithoutRainbow = Except<Foo, 'rainbow'>;
//=> {unicorn: string}

Try it in the TypeScript Playground

API

Click the type names for complete docs.

Basic

Utilities

Type Guard

JSON

Structured clone

Function

Async

String

Array

Numeric

Change case

Miscellaneous

Improved built-in

Declined types

If we decline a type addition, we will make sure to document the better solution here.

Alternative type names

If you know one of our types by a different name, add it here for discovery.

Tips

Extending existing types

“Cannot be named” errors in declaration files

When TypeScript generates declaration files, it writes out the inferred type of each export. If that type uses a type from this package, it can refer to an internal helper type or symbol, and you get an error such as TS2742, TS2883, TS4023, or TS4058 (“The inferred type of 'x' cannot be named without a reference to…”). Internal types and symbols are not part of the public API, so they cannot be imported. This is a TypeScript limitation. Add an explicit type annotation to the export instead:

import type {EmptyObject, ReadonlyDeep} from 'type-fest';

type Config = {
	server: {
		port: number;
	};
};

declare function freeze<Value>(value: Value): ReadonlyDeep<Value>;

export const config: ReadonlyDeep<Config> = freeze({server: {port: 8080}});

export function copy(value: EmptyObject): EmptyObject {
	return {...value};
}

Also make sure type-fest is a direct dependency of the package that generates the declaration files.

Built-in types

There are many advanced types most users don't know about.

You can find some examples in the TypeScript docs.

Maintainers

License

SPDX-License-Identifier: (MIT OR CC0-1.0)

type-fest (sindresorhus/type-fest)

Ищем в базе…

Что это такое?type-fest — это набор основных типов для TypeScript — вспомогательных типов, которые, по мнению автора, должны были быть встроены в язык. Они покрывают объекты, объединения, строки, массивы, кортежи и функции.
Это библиотека для рантайма или просто описания типов?Только типы — описания, которые компилятор использует во время сборки; в вашем приложении не выполняется ни строчки кода. Для функций рантайма автор выпускает отдельный пакет-компаньон, ts-extras.
Как добавить его в проект?Установите как зависимость командой npm install type-fest и импортируйте нужные типы — а можно и вовсе обойтись без пакета и просто скопировать себе только те описания, которые нужны.
Проекту нужна какая-то особая настройка TypeScript?Да — TypeScript 5.9 или новее, ESM и строгий режим ({strict: true}) в tsconfig; более старые проекты и проекты без строгого режима его не примут. Учтите также, что README на GitHub описывает невыпущенную dev-версию, поэтому документация по релизам лежит на npm.
Какие типы туда входят?Больше сотни, в трёх группах: Basic (Primitive, Class, TypedArray), Utilities (Except, Merge, LiteralUnion, PartialDeep, Get...) и Type Guards (If, IsLiteral, IsNumericLiteral).
Какие типы стоит узнать в первую очередь?Except убирает ключи из типа объекта, Merge объединяет два типа, LiteralUnion сохраняет автодополнение в IDE для литеральных объединений, а Get достаёт вложенное свойство — как .get() в Lodash.
Если я скопирую типы в свой код, нужно ли указывать авторство?Нет — type-fest распространяется по лицензии CC0-1.0, то есть фактически как общественное достояние, и в README прямо сказано, что копирование нужных типов не требует указания авторства.
Он поспевает за новыми версиями TypeScript?Скорее всего да: в CI репозитория есть canary-workflow, который тестирует невыпущенные сборки TypeScript, а README призывает предлагать типы, достойные самого языка, напрямую в проект TypeScript.
Какие есть похожие проекты?date-fns, DefinitelyTyped, cz-cli, nuqs, reselect, Inquirer.js, inflector, react-icons
Автор
sindresorhus
Размер
5.3 MB
Звёзды
17.5K
Возраст
7 г
Коммиты · 90 дней