Reputation: 43
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"}
}
Upvotes: 1
Views: 73
Reputation: 121
"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.
Upvotes: 0
Reputation: 249536
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
Upvotes: 1