只是好奇 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/