What is “type '{}'”?

前端 未结 3 1368
我寻月下人不归
我寻月下人不归 2020-12-11 14:45

In TypeScript, what exactly is type \'{}\' and how does it relate to other built-in types?

For example, the last line of the following example gives

3条回答
  •  无人及你
    2020-12-11 15:15

    type {}

    Consider the object type { id: number, name: string }, which represents a 2-field object. Legal values of this type include { id: 1, name: "Foo" } and { id: 2, name: "Bar" }.

    The type object {} represents a 0-field object. The only legal value of this type is an empty object: {}.

    So the value { id: 1, name: "Foo" } is of type { id: number, name: string }, and the value {} (i.e. an empty object) is of type {}.

    The error

    The error seems to be a bug in the TypeScript compiler (I submitted an issue here). It fails to infer the type arguments in the call to call. You can work around this by explicitly specifying the type arguments:

    let the_answer: number = call>(get_the_answer);
    

    But it's simpler and more straightforward to use a single type argument instead, as @NitzanTomer suggested:

    function call(fn: NoArgsFn): T {
      return fn();
    }
    

    EDIT: I issue I submitted was closed as a duplicate of #7234 which is to be fixed before the release of TypeScript 2.0.

提交回复
热议问题