Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
666 views
in Technique[技术] by (71.8m points)

typescript - What is "type '{}'"?

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 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);
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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();
}

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...