{} type?It's the empty object type.
The empty object type is weird. Oh sure, at first, it might look like it's working, because it won't let you set a key on that object.
const y: {} = {};
// Element implicitly has an 'any' type because expression of type '"a"' can't be used to index type '{}'.
// Property 'a' does not exist on type '{}'.ts(7053)
y["a"] = 1;But look at all the other things it will let you do!
let x: {};
x = 1; // OK
x = "hello"; // OK
x = []; // OK
x = { key: "value" }; // OKIt will even let you reassign it to another object!
const z = { name: "Adit", age: 30 };
let x: {} = {};
x = z; // OKIf you type a variable as the empty object type, you can set it to anything except null or undefined.
x = null; // Error
x = undefined; // ErrorThis is because TypeScript uses structural typing. For example, this is valid.
type Animal = {
name: string;
};
type Pet = {
name: string;
};
let animal: Animal = { name: "Fido" };
let pet: Pet = { name: "Fido" };
animal = pet; // OKEven though these variables have two different types with two different names, structurally, both types are the same, so TypeScript considers them the same.
In JavaScript, almost everything is an object (sort of; nuance explained here). For example, type in any of these in a developer console and you will see a dropdown.
"hello". // dropdown
(1). // dropdown
true. // dropdownThe dropdown is showing you the instance methods you can call these, because they are objects. Since they are objects, because of structural typing, any of them can be assigned to the empty object type.
But these are not objects:
null. // no dropdown
undefined. // no dropdownSo, you can't assign them to the empty object type. In general, you should try to avoid this type. If you actually want to type something as an empty object, use
const x: Record<string, never> = {};And it works as expected:
let x: Record<string, never> = {};
// Type 'number' is not assignable to type 'never'.ts(2322)
x["a"] = 1;
// Type 'number' is not assignable to type 'Record<string, never>'.ts(2322)
x = 1;