3

Could somebody explain me which is the difference between {} and any?

for example, which's the difference between setting generic interface parameter as Interface<{}> or as Interface<any>.

Any ideas?

Jordi
  • 20,868
  • 39
  • 149
  • 333
  • related: https://stackoverflow.com/questions/18961203/typescript-any-vs-object and https://stackoverflow.com/questions/21396195/what-are-the-differences-between-the-empty-object-type-and-object – artem Nov 16 '17 at 22:06
  • 2
    Possible duplicate of [TypeScript any vs Object](https://stackoverflow.com/questions/18961203/typescript-any-vs-object) – Leon Nov 16 '17 at 22:06
  • Using `{}` is really a javascript thing, because in JS you don't have types. In Typescript you can define a type (by using `type`, `class` or `interface`) and then you can define your object to be of that type. – Kokodoko Nov 16 '17 at 22:40

2 Answers2

5

to better understand what does {} mean, check https://blog.mariusschulz.com/2017/02/24/typescript-2-2-the-object-type

{} is a top type. What does it mean ? if you annotate something as {} it can be any of following types: string | number | boolean | object | {[key:string]: any} | Object | any[]

const test1: {} = 'hello'
const test2: {} = 123
const test3: {} = false
const test4: {} = {foo:'bar'}

Although null | undefined is not allowed

// Expect errors
const test6: {} = null
const test7: {} = undefined

Playground link

any completely turns off type checker and you can do anything "crazy", that you've been used to from vanilla JS. PRO TIP: don't use this at home :) definitely use no-any rule within ts-lint

hotell
  • 528
  • 1
  • 5
  • 16
  • 2
    This seems right but where in the docs does it explicitly state those types above are compatible? Can't seem to find that anywhere... – stephen_liu Apr 03 '20 at 22:09
  • there is no mention in the docs as there is new "replacement" as a public API from typescript - called `unknown` which should be used instead. - So `{}` was former bottom type (rather private API of TS) - since introduction of `unknown` , `unknown` is the new bottom type and should be used only – hotell Aug 09 '20 at 09:54
-3

So there are types in JavaScript. Like number, string, object and boolean. any matches any of these types. {} just matches an empty object.

function fn1(foo: any): void {}
function fn2(foo: {}): void {}

fn1(23); // OK
fn1('test'); // OK
fn1(undefined); // OK
fn2({}); // OK
fn2(23); // Not OK
fn2(null); // Not OK
Rudolph Gottesheim
  • 1,671
  • 1
  • 17
  • 30
  • 1
    `any` is not just another type, `any` suppresses typechecking: `function f(): any { }; let a = f(); a.whatever.ever.ever()` compiles without errors. – artem Nov 16 '17 at 22:47
  • 1
    It seems that `{}` does actually not just match an empty object, but seems to rather be equivalent to `object`. So your example `fn2(23)` does actually not cause any error. – cdauth Nov 23 '20 at 23:47