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;
}
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.
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", };
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With