Search code examples
typescripttypestypescript-typings

Define an empty object type in TypeScript


I'm looking for ways to define an empty object type that can't hold any values.

type EmptyObject = {}

const MyObject: EmptyObject = {
  thisShouldNotWork: {},
};

Objects with the type are free to add any properties. How can I force MyObject to always be an empty object instead?

My actual use case is using the EmptyObject type inside an interface.

interface SchemaWithEmptyObject {
  emptyObj: EmptyObject; 
}

Solution

  • 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.