GitHub image
type-fest
⌘K
Exports
Readme
Object
15
Except
Docs
Import
Tests
3
References
2

Create a type from an object type without certain keys.

This type is a stricter version of Omit. The Omit type does not restrict the omitted keys to be keys present on the given type, while Except does. The benefits of a stricter type are avoiding typos and allowing the compiler to pick up on rename refactors automatically.

This type was proposed to the TypeScript team, which declined it, saying they prefer that libraries implement stricter versions of the built-in types (microsoft/TypeScript#30825).

type Except<ObjectType', KeysType'> = { }
Example
1
2
3
4
5
6
7
8
9
10
11
import {Except} from 'type-fest';
type Foo = {
a: number;
b: string;
c: boolean;
};
type FooWithoutA = Except<Foo, 'a' | 'c'>;
//=> {b: string};
Mutable
Docs
Import
Tests
3
References
2

Useful to flatten the type output to improve type hints shown in editors. And also to transform an interface into a type to aide with assignability.

type Simplify<T'> = { }
Example
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import {Mutable} from 'type-fest';
type Foo = {
readonly a: number;
readonly b: readonly string[]; // To show that only the mutability status of the properties, not their values, are affected.
readonly c: boolean;
};
const mutableFoo: Mutable<Foo> = {a: 1, b: ['2'], c: true};
mutableFoo.a = 3;
mutableFoo.b[0] = 'new value'; // Will still fail as the value of property "b" is still a readonly type.
mutableFoo.b = ['something']; // Will work as the "b" property itself is no longer readonly.
type SomeMutable = Mutable<Foo, 'b' | 'c'>;
// type SomeMutable = {
// readonly a: number;
// b: readonly string[]; // It's now mutable. The type of the property remains unaffected.
// c: boolean; // It's now mutable.
// }
Merge
Docs
Import
Tests
3
References
2

Useful to flatten the type output to improve type hints shown in editors. And also to transform an interface into a type to aide with assignability.

type Simplify<T'> = { }
Example
1
2
3
4
5
6
7
8
9
10
11
12
13
import {Merge} from 'type-fest';
type Foo = {
a: number;
b: string;
};
type Bar = {
b: number;
};
const ab: Merge<Foo, Bar> = {a: 1, b: 2};
MergeExclusive
Docs
Import
Tests
3
References
2

Create a type that has mutually exclusive keys.

This type was inspired by this comment.

This type works with a helper type, called Without. Without<FirstType, SecondType> produces a type that has only keys from FirstType which are not present on SecondType and sets the value type for these keys to never. This helper type is then used in MergeExclusive to remove keys from either FirstType or SecondType.

type MergeExclusive<FirstType', SecondType'> = MergeExclusive<FirstType, SecondType>
Example
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import {MergeExclusive} from 'type-fest';
interface ExclusiveVariation1 {
exclusive1: boolean;
}
interface ExclusiveVariation2 {
exclusive2: string;
}
type ExclusiveOptions = MergeExclusive<ExclusiveVariation1, ExclusiveVariation2>;
let exclusiveOptions: ExclusiveOptions;
exclusiveOptions = {exclusive1: true};
//=> Works
exclusiveOptions = {exclusive2: 'hi'};
//=> Works
exclusiveOptions = {exclusive1: true, exclusive2: 'hi'};
//=> Error
RequireAtLeastOne
Docs
Import
Tests
3
References
2

Create a type that requires at least one of the given keys. The remaining keys are kept as is.

type RequireAtLeastOne<ObjectType', KeysType' = keyof ObjectType> =
&
{ [Key in KeysType]-?: Required<Pick<ObjectType, Key>> & Partial<Pick<ObjectType, Exclude<KeysType, Key>>>; }[KeysType]
&
Except<ObjectType', KeysType'>
Example
1
2
3
4
5
6
7
8
9
10
11
12
13
14
import {RequireAtLeastOne} from 'type-fest';
type Responder = {
text?: () => string;
json?: () => string;
secure?: boolean;
};
const responder: RequireAtLeastOne<Responder, 'text' | 'json'> = {
json: () => '{"message": "ok"}',
secure: true
};
RequireExactlyOne
Docs
Import
Tests
3
References
2

Create a type that requires exactly one of the given keys and disallows more. The remaining keys are kept as is.

Use-cases:

  • Creating interfaces for components that only need one of the keys to display properly.
  • Declaring generic keys in a single place for a single use-case that gets narrowed down via RequireExactlyOne.

The caveat with RequireExactlyOne is that TypeScript doesn't always know at compile time every key that will exist at runtime. Therefore RequireExactlyOne can't do anything to prevent extra keys it doesn't know about.

type RequireExactlyOne<ObjectType', KeysType' = keyof ObjectType> =
&
{ [Key in KeysType]: Required<Pick<ObjectType, Key>> & Partial<Record<Exclude<KeysType, Key>, never>>; }[KeysType]
&
Omit<ObjectType', KeysType'>
Example
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import {RequireExactlyOne} from 'type-fest';
type Responder = {
text: () => string;
json: () => string;
secure: boolean;
};
const responder: RequireExactlyOne<Responder, 'text' | 'json'> = {
// Adding a `text` key here would cause a compile error.
json: () => '{"message": "ok"}',
secure: true
};
RequireAllOrNone
Docs
Import
Tests
3
References
2

Create a type that requires all of the given keys or none of the given keys. The remaining keys are kept as is.

Use-cases:

  • Creating interfaces for components with mutually-inclusive keys.

The caveat with RequireAllOrNone is that TypeScript doesn't always know at compile time every key that will exist at runtime. Therefore RequireAllOrNone can't do anything to prevent extra keys it doesn't know about.

type RequireAllOrNone<ObjectType', KeysType' = never> =
|
(Required<Pick<ObjectType', KeysType'>> & Omit<ObjectType', KeysType'>)
|
(Partial<Record<KeysType', never>> & Omit<ObjectType', KeysType'>)
Example
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import {RequireAllOrNone} from 'type-fest';
type Responder = {
text?: () => string;
json?: () => string;
secure: boolean;
};
const responder1: RequireAllOrNone<Responder, 'text' | 'json'> = {
secure: true
};
const responder2: RequireAllOrNone<Responder, 'text' | 'json'> = {
text: () => '{"message": "hi"}',
json: () => '{"message": "ok"}',
secure: true
};
PartialDeep
Docs
Import
Tests
3
References
2

Create a type from another type with all keys and nested keys set to optional.

Use-cases:

  • Merging a default settings/config object with another object, the second object would be a deep partial of the default object.
  • Mocking and testing complex entities, where populating an entire object with its keys would be redundant in terms of the mock or test.
type PartialDeep<T'> = PartialDeep<T>
Example
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import {PartialDeep} from 'type-fest';
const settings: Settings = {
textEditor: {
fontSize: 14;
fontColor: '#000000';
fontWeight: 400;
}
autocomplete: false;
autosave: true;
};
const applySavedSettings = (savedSettings: PartialDeep<Settings>) => {
return {...settings, ...savedSettings};
}
settings = applySavedSettings({textEditor: {fontWeight: 500}});
ReadonlyDeep
Docs
Import
Tests
3
References
2

Convert objects, Maps, Sets, and Arrays and all of their keys/elements into immutable structures recursively.

This is useful when a deeply nested structure needs to be exposed as completely immutable, for example, an imported JSON module or when receiving an API response that is passed around.

Please upvote this issue if you want to have this type as a built-in in TypeScript.

type ReadonlyDeep<T'> = ReadonlyDeep<T>
Example
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// data.json
{
"foo": ["bar"]
}
// main.ts
import {ReadonlyDeep} from 'type-fest';
import dataJson = require('./data.json');
const data: ReadonlyDeep<typeof dataJson> = dataJson;
export default data;
// test.ts
import data from './main';
data.foo.push('bar');
//=> error TS2339: Property 'push' does not exist on type 'readonly string[]'
SetOptional
Docs
Import
Tests
3
References
2

Useful to flatten the type output to improve type hints shown in editors. And also to transform an interface into a type to aide with assignability.

type Simplify<T'> = { }
Example
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import {SetOptional} from 'type-fest';
type Foo = {
a: number;
b?: string;
c: boolean;
}
type SomeOptional = SetOptional<Foo, 'b' | 'c'>;
// type SomeOptional = {
// a: number;
// b?: string; // Was already optional and still is.
// c?: boolean; // Is now optional.
// }
SetRequired
Docs
Import
Tests
3
References
2

Useful to flatten the type output to improve type hints shown in editors. And also to transform an interface into a type to aide with assignability.

type Simplify<T'> = { }
Example
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import {SetRequired} from 'type-fest';
type Foo = {
a?: number;
b: string;
c?: boolean;
}
type SomeRequired = SetRequired<Foo, 'b' | 'c'>;
// type SomeRequired = {
// a?: number;
// b: string; // Was already required and still is.
// c: boolean; // Is now required.
// }
ValueOf
Docs
Import
Tests
3
References
2

Create a union of the given object's values, and optionally specify which keys to get the values from.

Please upvote this issue if you want to have this type as a built-in in TypeScript.

type ValueOf<ObjectType', ValueType' = keyof ObjectType> = ValueOf<ObjectType, ValueType>
Example
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
// data.json
{
'foo': 1,
'bar': 2,
'biz': 3
}
// main.ts
import {ValueOf} from 'type-fest';
import data = require('./data.json');
export function getData(name: string): ValueOf<typeof data> {
return data[name];
}
export function onlyBar(name: string): ValueOf<typeof data, 'bar'> {
return data[name];
}
// file.ts
import {getData, onlyBar} from './main';
getData('foo');
//=> 1
onlyBar('foo');
//=> TypeError ...
onlyBar('bar');
//=> 2
ConditionalExcept
Docs
Import
Tests
3
References
2

Create a type from an object type without certain keys.

This type is a stricter version of Omit. The Omit type does not restrict the omitted keys to be keys present on the given type, while Except does. The benefits of a stricter type are avoiding typos and allowing the compiler to pick up on rename refactors automatically.

This type was proposed to the TypeScript team, which declined it, saying they prefer that libraries implement stricter versions of the built-in types (microsoft/TypeScript#30825).

type Except<ObjectType', KeysType'> = { }
Examples
1
2
3
4
5
6
7
8
9
10
11
12
13
import {Primitive, ConditionalExcept} from 'type-fest';
class Awesome {
name: string;
successes: number;
failures: bigint;
run() {}
}
type ExceptPrimitivesFromAwesome = ConditionalExcept<Awesome, Primitive>;
//=> {run: () => void}
1
2
3
4
5
6
7
8
9
10
11
12
import {ConditionalExcept} from 'type-fest';
interface Example {
a: string;
b: string | number;
c: () => void;
d: {};
}
type NonStringKeysOnly = ConditionalExcept<Example, string>;
//=> {b: string | number; c: () => void; d: {}}
ConditionalKeys
Docs
Import
Tests
3
References
2

Extract the keys from a type where the value type of the key extends the given Condition.

Internally this is used for the ConditionalPick and ConditionalExcept types.

type ConditionalKeys<Base', Condition'> = NonNullable<
{ [Key in keyof Base]: Base[Key] extends Condition ? Key : never; }[keyof Base],
>
Examples
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import {ConditionalKeys} from 'type-fest';
interface Example {
a: string;
b: string | number;
c?: string;
d: {};
}
type StringKeysOnly = ConditionalKeys<Example, string>;
//=> 'a'
```
To support partial types, make sure your `Condition` is a union of undefined (for example, `string | undefined`) as demonstrated below.
1
2
3
type StringKeysAndUndefined = ConditionalKeys<Example, string | undefined>;
//=> 'a' | 'c'
ConditionalPick
Docs
Import
Tests
3
References
2

Pick keys from the shape that matches the given Condition.

This is useful when you want to create a new type from a specific subset of an existing type. For example, you might want to pick all the primitive properties from a class and form a new automatically derived type.

type ConditionalPick<Base', Condition'> = Pick<Base', NonNullable>
Examples
1
2
3
4
5
6
7
8
9
10
11
12
13
import {Primitive, ConditionalPick} from 'type-fest';
class Awesome {
name: string;
successes: number;
failures: bigint;
run() {}
}
type PickPrimitivesFromAwesome = ConditionalPick<Awesome, Primitive>;
//=> {name: string; successes: number; failures: bigint}
1
2
3
4
5
6
7
8
9
10
11
12
import {ConditionalPick} from 'type-fest';
interface Example {
a: string;
b: string | number;
c: () => void;
d: {};
}
type StringKeysOnly = ConditionalPick<Example, string>;
//=> {a: string}
Type
2
LiteralUnion
Docs
Import
Tests
3
References
2

Allows creating a union type by combining primitive types and literal types without sacrificing auto-completion in IDEs for the literal type part of the union.

Currently, when a union type of a primitive type is combined with literal types, TypeScript loses all information about the combined literals. Thus, when such type is used in an IDE with autocompletion, no suggestions are made for the declared literals.

This type is a workaround for Microsoft/TypeScript#29729. It will be removed as soon as it's not needed anymore.

type LiteralUnion<LiteralType', BaseType'> = LiteralType' | (BaseType' & { _?: never })
Example
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import {LiteralUnion} from 'type-fest';
// Before
type Pet = 'dog' | 'cat' | string;
const pet: Pet = '';
// Start typing in your TypeScript-enabled IDE.
// You **will not** get auto-completion for `dog` and `cat` literals.
// After
type Pet2 = LiteralUnion<'dog' | 'cat', string>;
const pet: Pet2 = '';
// You **will** get auto-completion for `dog` and `cat` literals.
Opaque
Docs
Import
Tests
3
References
2

Create an opaque type, which hides its internal details from the public, and can only be created by being used explicitly.

The generic type parameter can be anything. It doesn't have to be an object.

Read more about opaque types.

There have been several discussions about adding this feature to TypeScript via the opaque type operator, similar to how Flow does it. Unfortunately, nothing has (yet) moved forward: - Microsoft/TypeScript#202 - Microsoft/TypeScript#15408 - Microsoft/TypeScript#15807

type Opaque<Type', Token' = unknown> = Type' & Tagged<Token'>
Example
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
import {Opaque} from 'type-fest';
type AccountNumber = Opaque<number, 'AccountNumber'>;
type AccountBalance = Opaque<number, 'AccountBalance'>;
// The `Token` parameter allows the compiler to differentiate between types, whereas "unknown" will not. For example, consider the following structures:
type ThingOne = Opaque<string>;
type ThingTwo = Opaque<string>;
// To the compiler, these types are allowed to be cast to each other as they have the same underlying type. They are both `string & { __opaque__: unknown }`.
// To avoid this behaviour, you would instead pass the "Token" parameter, like so.
type NewThingOne = Opaque<string, 'ThingOne'>;
type NewThingTwo = Opaque<string, 'ThingTwo'>;
// Now they're completely separate types, so the following will fail to compile.
function createNewThingOne (): NewThingOne {
// As you can see, casting from a string is still allowed. However, you may not cast NewThingOne to NewThingTwo, and vice versa.
return 'new thing one' as NewThingOne;
}
// This will fail to compile, as they are fundamentally different types.
const thingTwo = createNewThingOne() as NewThingTwo;
// Here's another example of opaque typing.
function createAccountNumber(): AccountNumber {
return 2 as AccountNumber;
}
function getMoneyForAccount(accountNumber: AccountNumber): AccountBalance {
return 4 as AccountBalance;
}
// This will compile successfully.
getMoneyForAccount(createAccountNumber());
// But this won't, because it has to be explicitly passed as an `AccountNumber` type.
getMoneyForAccount(2);
// You can use opaque values like they aren't opaque too.
const accountNumber = createAccountNumber();
// This will not compile successfully.
const newAccountNumber = accountNumber + 2;
// As a side note, you can (and should) use recursive types for your opaque types to make them stronger and hopefully easier to type.
type Person = {
id: Opaque<number, Person>;
name: string;
};
Async
3
Promisable
Docs
Import
Tests
3
References
2

Create a type that represents either the value or the value wrapped in PromiseLike.

Use-cases:

  • A function accepts a callback that may either return a value synchronously or may return a promised value.
  • This type could be the return type of Promise#then(), Promise#catch(), and Promise#finally() callbacks.

Please upvote this issue if you want to have this type as a built-in in TypeScript.

type Promisable<T'> = T' | PromiseLike<T'>
Example
1
2
3
4
5
6
7
8
9
10
import {Promisable} from 'type-fest';
async function logger(getLogEntry: () => Promisable<string>): Promise<void> {
const entry = await getLogEntry();
console.log(entry);
}
logger(() => 'foo');
logger(() => Promise.resolve('bar'));
PromiseValue
Docs
Import
Tests
3
References
2
type PromiseValue<PromiseType'> = PromiseValue<PromiseType>
Example
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import {PromiseValue} from 'type-fest';
type AsyncData = Promise<string>;
let asyncData: PromiseValue<AsyncData> = Promise.resolve('ABC');
type Data = PromiseValue<AsyncData>;
let data: Data = await asyncData;
// Here's an example that shows how this type reacts to non-Promise types.
type SyncData = PromiseValue<string>;
let syncData: SyncData = getSyncData();
// Here's an example that shows how this type reacts to recursive Promise types.
type RecursiveAsyncData = Promise<Promise<string> >;
let recursiveAsyncData: PromiseValue<RecursiveAsyncData> = Promise.resolve(Promise.resolve('ABC'));
AsyncReturnType
Docs
Import
Tests
3
References
2

Unwrap the return type of a function that returns a Promise.

There has been discussion about implementing this type in TypeScript.

type AsyncReturnType<Target'> = PromiseValue<ReturnType>
Example
1
2
3
4
5
6
7
8
9
import {AsyncReturnType} from 'type-fest';
import {asyncFunction} from 'api';
// This type resolves to the unwrapped return type of `asyncFunction`.
type Value = AsyncReturnType<typeof asyncFunction>;
async function doSomething(value: Value) {}
asyncFunction().then(value => doSomething(value));
Description
A collection of essential TypeScript types
Install
yarn add type-fest
Copy
Details
(MIT OR CC0-1.0) License
0 Dependencies
Native TypeScript Package
Metrics
Weekly Downloads