Define an empty object type in TypeScript

10,002

Solution 1

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.

Solution 2

type EmptyObject = Record<any, never>

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

Solution 3

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

Share:
10,002
Mikey
Author by

Mikey

Software engineer with a passion for education

Updated on June 12, 2022

Comments

  • Mikey
    Mikey almost 2 years

    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; 
    }
    
  • n1ru4l
    n1ru4l almost 3 years
    Unfortunately, this solution does not work when you want to discriminate against an intersection union type: type Union = EmptyObject | { id: string }; const a: Union = {}; const b: string = a.id // this should raise an error but does not.
  • cprcrack
    cprcrack about 2 years
    Or Record<string, never> to avoid using an explicit any (eslint error)