【问题标题】:What is the GenericType argument in a Typescript Promise<GenericType> definition?Typescript Promise<GenericType> 定义中的 GenericType 参数是什么?
【发布时间】:2018-06-08 11:16:40
【问题描述】:

只是好奇 Typescripts 中的泛型类型Promise&lt;GenericType&gt; 是否定义了传递给then 处理程序的对象类型?

例如这有效:

    const pr:Promise<Array<Number>> = Promise.resolve([1, 2, 3]);

    const handler = (arg:Array<Number>)=> {
       console.dir(arg);
    }

    pr.then(handler);

另一个相关问题。如果我们将handler 设为handler:Function,那么vscode 会抱怨/在代码的pr.then(handler 部分下绘制红色曲线。 typescript 有可以分配给处理函数的类型吗?

【问题讨论】:

  • Promise 只是异步值的容器,就像数组是多个值的容器一样。您必须指定它们包含的事物的类型。
  • 确实 - 只是想验证 GenericType 部分是返回类型,它是 promise 执行的异步操作的结果吗?

标签: javascript typescript promise


【解决方案1】:

只是想验证 GenericType 部分是返回类型,它是 Promise 执行的异步操作的结果吗?

不完全是。您的示例中没有泛型类型:您为所有内容提供了具体类型。

你想要的(我认为)是这样的:

const pr:Promise<Array<Number>> = Promise.resolve([1, 2, 3]);

// handler here is declared with type Array<Number> -> void
const handler = (arg:Array<Number>): void => { // NOTE: void
   console.dir(arg);
}

pr.then(handler);

为了说明类型保存(及其必要性):

// doubleToString has type Number -> String
const doubleToString = (n: Number): String => (n * 2).toString();
const doubledAndStringed: Promise<Array<String>> = pr.then(arr => arr.map(doubleToString));

而以下失败:

const repeatString = (s: String): String => s.repeat(1);
const repeated: Promise<Array<String>> = pr.then(arr => arr.map(repeatString))

如果您有一个根据参数类型返回 Promise 的函数,则使用泛型类型:

const wrap = (x: T): Promise<T> => Promise.resolve(x);

这里T是泛型类型,打字稿会保留参数的特定类型:

const wrappedString: Promise<String> = wrap('hello!');

无论您是否对其进行注释,wrappedString 都会具有该具体类型。

【讨论】:

    猜你喜欢
    • 2020-12-23
    • 2016-10-26
    • 2018-02-10
    • 1970-01-01
    • 1970-01-01
    • 2010-12-01
    • 2021-09-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多