简体   繁体   中英

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 {} ?

{} 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM