Define an empty object type in TypeScript

Acording to VSC linter type emtyObj = Record<string, never> .


type EmptyObject = Record<any, never>

This is equivalent to Maciej Sikora's answer but makes use of the Record utility type.


type EmptyObject = {
    [K in any] : never
}

const one: EmptyObject = {}; // yes ok
const two: EmptyObject = {a: 1}; // error

What we are saying here is that all eventual properties of our EmptyObject can be only never, and as never has no representing value, creating such property is not possible, therefor the object will remain empty, as this is the only way we can create it without compilation error.


There are several options for defining an empty object type, and it completely depends on the side-effects you want regarding your linter and typescript errors when accessing or setting properties. These are the options I tried:

// Option A:
let objA: Record<any, never> = {}; // Typescript-ESLint error: Unexpected any. Specify a different type.
objA = { prop: 'value' }; // Typescript error: Type 'string' is not assignable to type 'never'.
console.log(objA.prop);
console.log(objA.nonExistingProp); // No error!!!

// Option B:
let objB: Record<string, never> = {};
objB = { prop: 'value' }; // Typescript error: Type 'string' is not assignable to type 'never'.
console.log(objB.prop);
console.log(objB.nonExistingProp); // No error!!!

// Option C:
let objC: Record<never, never> = {};
objC = { prop: 'value' };
console.log(objC.prop); // Typescript error: Property 'prop' does not exist on type 'Record<never, never>'
console.log(objC.nonExistingProp); // Typescript error: Property 'nonExistingProp' does not exist on type 'Record<never, never>'.

TLDR: Record<string, never> raises errors when setting properties to the empty object. Record<never, never> raises errors when accessing properties of the empty object. I have yet to find a solution that raises errors in both cases.

Personally I went with option C for my current use-case, because I wanted an error to happen if I try to access a property of an empty object, but you may not want that!