doberkofler
doberkofler

Reputation: 10361

What type is identified with `{}` in TypeScript

I'm using the type {} to identify an object in TypeScript but it pretty much seems to allow anything except null and undefined:

function foo(): {} {
  return "string";
}

The above example is valid TypeScript, so what type is declared in TypeScript when using {} ?

Upvotes: 1

Views: 74

Answers (1)

Titian Cernicova-Dragomir
Titian Cernicova-Dragomir

Reputation: 250006

{} will be compatible with any type (it has no required properties, index or call signatures).

If you want to return something that is not a primitive you can use object:

function foo(): object {
    return "string"; // error now 
}

The object type is documented here. Also, from the PR introducing the object type :

The object type is the equivalent of {} minus the assignability of other basic type, that means that:

  1. any other basic types are not assignable to object
  2. any non-basic type is assignable to object
  3. object is only assignable to {} and any

Upvotes: 3

Related Questions