kecheng.wx
kecheng.wx

Reputation: 43

why 'function type' can apply to '{} type'

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

Answers (2)

jean3xw
jean3xw

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

Titian Cernicova-Dragomir
Titian Cernicova-Dragomir

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

Related Questions