Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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; 
}
like image 235
Mikey Avatar asked Feb 07 '20 10:02

Mikey


People also ask

What is the type of an empty object in TypeScript?

The TypeScript object type represents any value that is not a primitive value. The Object type, however, describes functionality that available on all objects. The empty type {} refers to an object that has no property on its own.

How do I declare and initialize an object in TypeScript?

To initialize an object in TypeScript, we can create an object that matches the properties and types specified in the interface. export interface Category { name: string; description: string; } const category: Category = { name: "My Category", description: "My Description", };

Is null or empty in TypeScript?

Null refers to a value that is either empty or doesn't exist. null means no value. To make a variable null we must assign null value to it as by default in typescript unassigned values are termed undefined. We can use typeof or '==' or '===' to check if a variable is null or undefined in typescript.

How do you create an empty object in JavaScript?

You can use object literal or object constructor to create an empty object in JavaScript. There is no benefit to using new Object(); – whereas {}; can make your code more compact, and more readable. The only difference is One of them is an object literal, and the other one is a constructor.


1 Answers

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.

like image 156
Maciej Sikora Avatar answered Sep 21 '22 12:09

Maciej Sikora