1

Look at the code below, with no errors, I want to know why function type can apply to {} type

"typescript": "~2.9.1",

interface IIndexCtlState {
    x: {}
}
const state: IIndexCtlState = {
    x: function y() {return "sdf"}
}
Carlos Cavero
  • 3,011
  • 5
  • 21
  • 41
kecheng.wx
  • 43
  • 2

2 Answers2

1

Typing in typescript is structural, {} defines a type with no members. Any other type can be compatible with this type. Primitives, functions, other objects, anything:

let s: {};
s = 1;
s = ""
s = () => ""
s = null // err under strictNullChecks

Under strict null checks, null and undefined are not assignable to {}. But other than that anything can be assigned to {}.

If you want to represent something that is an object the object type might be better but functions are still allowed (since functions are objects)

let s: object;
s = 1; //err
s = "" // err
s = () => ""
s = { foo: ""};
s = null // err under strictNullChecks
Titian Cernicova-Dragomir
  • 230,986
  • 31
  • 415
  • 357
0

"I don't know about typescript, but in javascript, (almost) everything is an object, including functions – Jaromanda X 10 mins ago " Nope it's the exacte opposite, everything is a Function in JavaScript, meaning Objects are Functions so are primary values. for example Object extends(inherit) Function and not the opposite.

jean3xw
  • 121
  • 7
  • This question was not about `Object` constructor, but about object type `{}` which is not a function. See also https://stackoverflow.com/questions/3449596/every-object-is-a-function-and-every-function-is-object-which-is-correct – artem Apr 24 '19 at 13:30