什么是“类型 '{}'"? [英] What is "type '{}'"?

查看:114
本文介绍了什么是“类型 '{}'"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 TypeScript 中,type '{}' 到底是什么,它与其他内置类型有什么关系?

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

例如,下面例子的最后一行给出了Type '{}' is notassignable to type 'number',我也不是很清楚type {} 是在这种情况下,或者实际上是如何产生的:

For example, the last line of the following example gives Type '{}' is not assignable to type 'number', and I am not completely clear on what type {} is in this context, or indeed how it comes about:

// A function taking no arguments and returning T
type NoArgsFn<T> = () => T;

// An instance of NoArgsFn<number>
function get_the_answer(): number {
  return 42;
}

// Call the supplied function and return its value
function call<T, Fn extends NoArgsFn<T>>(fn: Fn): T {
  return fn();
}

// Expect this to be equivalent to `let the_answer: number = 42', but
// instead get "Type '{}' is not assignable to type 'number'"
let the_answer: number = call(get_the_answer);

推荐答案

type {}

考虑对象类型 { id: number, name: string },它表示一个 2-field 对象.此类型的合法值包括 { id: 1, name: "Foo" }{ id: 2, name: "Bar" }.

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" }.

类型对象 {} 表示一个 0 字段对象.此类型的唯一合法值是一个空对象:{}.

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

所以 value { id: 1, name: "Foo" }type { id: number, name: string }value {}(即空对象)是type {}.

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 {}.

该错误似乎是 TypeScript 编译器中的一个错误(我在此处提交了一个问题).它无法推断对 call 的调用中的类型参数.您可以通过显式指定类型参数来解决此问题:

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<number, NoArgsFn<number>>(get_the_answer);

但正如@NitzanTomer 建议的那样,使用单个类型参数更简单、更直接:

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

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

我提交的问题已作为 #7234 的副本关闭这将在 TypeScript 2.0 发布之前修复.

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

这篇关于什么是“类型 '{}'"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆