2

What type is a variable declared as below. In what case is it useful?

let x: {}

In the following type alias what is the meaning of {}. Is it equivalent to object or any? Why you would want to use {} as type instead of any? Does {}, in this case mean "instance" of empty object? (does make sense to me)

type MessageHandler<D, P> = (data: D, payload: P) => void
type MessageHandlerGeneric = MessageHandler<{}, any}

interface MessageHandlers {
  [index: string]: MessageHandlerGeneric
}

let handlers = MessageHandlers = {
  handler1: (data: string, payload: Pyaload),
  handler2: (data: Array<string>, payload: Payload)
}
Stanislav Stoyanov
  • 2,082
  • 2
  • 20
  • 22

2 Answers2

0

Object is more restrictive than any.

const b: Object = {};
b.myMethod();

won't compile (where myMethod() is not declared and known method). On the other hand, the method below compiles.

const c: any = {};
c.myMethod();

So, any can be anything (including null/undefined) on the other hand, If you explicitly use Object you will only be able to use the properties that are defined on the Object class.

Derviş Kayımbaşıoğlu
  • 28,492
  • 4
  • 50
  • 72
0

As others pointed out - once variable typed as any, compiler won't warn you if you'll try to access non existing properties or assign any value.

Regarding object vs {} - object is a type that represents the non-primitive type, i.e. any thing that is not number | string | boolean | symbol.

const foo: object = 'test'; // error 
const bar: {} = 'test'; // ok
Aleksey L.
  • 35,047
  • 10
  • 74
  • 84