简体   繁体   English

为什么TypeScript不会为此承诺链引发编译错误?

[英]Why does TypeScript not throw a compilation error for this promise chain?

I am still learning Typescript so maybe I am just fundamentally missing something but I do not understand why the following code throws a compilation error: 我仍在学习Typescript,所以也许我只是从根本上缺少一些东西,但我不明白为什么以下代码会引发编译错误:

// An example without Promises (does not compile)
function getAnObject(): Object {
  return { value: 'Hello' };
};

function doSomethingWithAString(input: String) {
  console.log(input);
}

const result = getAnObject();
// error TS2345: Argument of type 'Object' is not assignable to parameter of type 'String' 
doSomethingWithAString(result);

But the following code does not: 但是以下代码没有:

// A similar example with Promises (compiles)
function getAnObjectAsync(): Promise<Object> {
  return Promise.resolve({ value: 'Hello' });
};

getAnObjectAsync().then(function (result: String) {
// Throws a runtime exception
console.log(result.toUpperCase());
});

Why does TypeScript not complain that the onfulfilled function of the .then in the Promise example will receive result: Object ? 为什么不打字稿抱怨说, onfulfilled的功能.then在无极例如将得到result: Object

  • Am I doing something wrong? 难道我做错了什么?
  • Is there something I do not understand about this example? 关于此示例,我是否不了解?

That's because in TS, the type of functions' arguments are bivariant. 这是因为在TS中,函数参数的类型是双变量的。

In the case of a Promise.then, any passed function will be accepted provided its argument is either a subtype or supertype of the required type. 在Promise.then的情况下,任何传递的函数都将被接受,只要它的参数是所需类型的子类型或超类型。 So an object (Object, {}) will always be accepted. 因此,对象(Object,{})将始终被接受。 Fortunately, it will still catch widely incompatible types of course; 幸运的是,它当然仍然会捕获广泛不兼容的类型。 like expecting a { x: string} but receiving a { y: number } so it catches the majority of type errors. 就像期望{ x: string}但收到{ y: number }因此它捕获了大多数类型错误。

This is a design decision that has pros and cons; 这是一个具有优缺点的设计决策。 (personally, I think it was not worth it) they might even change it in the future since the last few versions of TS clearly take the direction of making TS more and more sound. (我个人认为这是不值得的),因为将来的TS版本显然会朝着使TS越来越声音的方向发展,所以他们甚至将来可能会对其进行更改。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM