javascript - Typescript Promise<Generic Type> 定义中的通用类型参数是什么?

标签 javascript typescript promise

只是好奇 Typescripts 中的泛型类型是否 Promise<GenericType> Promise 定义传递给 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 是否有可以分配给处理函数的类型?

最佳答案

Just wanted to verify that the GenericType part is the return type that is the result of the asynchronous operation that the promise performs?

不完全是。您的示例中没有通用类型:您已为所有内容指定了具体类型。

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

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 是泛型类型, typescript 将保留参数的特定类型:

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

这里 wrappedString 无论您是否注释它都会具有该具体类型。

关于javascript - Typescript Promise<Generic Type> 定义中的通用类型参数是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50759461/

相关文章:

javascript - 我可以让输入元素填充表格列的宽度吗?

javascript - javascript 查询选择器错误

javascript - 避免检索重复项(MYSQLi/PHP)

javascript - 具有延迟用户模块的身份验证模块

javascript - 在 Javascript 中的 API 调用之间使用 ASYNC/AWAIT 内的数组方法

javascript - gridster 根据内容自动调整高度和宽度

javascript - 使用 Map 与 Record 之间的差异以及何时使用

Angular - this.function 不是一个函数

javascript - js 将 try 嵌套在 catch block 中

unit-testing - 如何用 Mocha 测试 Promise catch