UNPKG

1.51 kBTypeScriptView Raw
1declare const emptyObjectSymbol: unique symbol;
2
3/**
4Represents a strictly empty plain object, the `{}` value.
5
6When you annotate something as the type `{}`, it can be anything except `null` and `undefined`. This means that you cannot use `{}` to represent an empty plain object ([read more](https://stackoverflow.com/questions/47339869/typescript-empty-object-and-any-difference/52193484#52193484)).
7
8@example
9```
10import type {EmptyObject} from 'type-fest';
11
12// The following illustrates the problem with `{}`.
13const foo1: {} = {}; // Pass
14const foo2: {} = []; // Pass
15const foo3: {} = 42; // Pass
16const foo4: {} = {a: 1}; // Pass
17
18// With `EmptyObject` only the first case is valid.
19const bar1: EmptyObject = {}; // Pass
20const bar2: EmptyObject = 42; // Fail
21const bar3: EmptyObject = []; // Fail
22const bar4: EmptyObject = {a: 1}; // Fail
23```
24
25Unfortunately, `Record<string, never>`, `Record<keyof any, never>` and `Record<never, never>` do not work. See {@link https://github.com/sindresorhus/type-fest/issues/395 #395}.
26
27@category Object
28*/
29export type EmptyObject = {[emptyObjectSymbol]?: never};
30
31/**
32Returns a `boolean` for whether the type is strictly equal to an empty plain object, the `{}` value.
33
34@example
35```
36import type {IsEmptyObject} from 'type-fest';
37
38type Pass = IsEmptyObject<{}>; //=> true
39type Fail = IsEmptyObject<[]>; //=> false
40type Fail = IsEmptyObject<null>; //=> false
41```
42
43@see EmptyObject
44@category Object
45*/
46export type IsEmptyObject<T> = T extends EmptyObject ? true : false;