我正在使用ReturnType<typeof function-name>
提取返回类型 - 非常有用。
现在正好函数的返回类型是Promise,我想进一步提取类型参数,例如:
const someFunction = (): Promise<MysteryType> => { ... some code ... }
type TheReturnType = ReturnType<typeof someFunction>
type ExtractTypeFromPromise = UNKNOWN<TheReturnType>
这目前可能吗?
最佳答案
TypeScript 文档有一个名为 "Type inference in conditional types" 的部分Unpacked<T>
给出了一个很好的答案类型定义:
type Unpacked<T> =
T extends (infer U)[] ? U :
T extends (...args: any[]) => infer U ? U :
T extends Promise<infer U> ? U :
T;
以及一些结果示例:
type T0 = Unpacked<string>; // string
type T1 = Unpacked<string[]>; // string
type T3 = Unpacked<Promise<string>>; // string
我不熟悉推断类型,所以感谢您帮助我学习新东西! :)
更新解决其他问题:
Is there a way to do this where you force the type at compile time to be of that instance.
Example:type T0 = UnpackedArray<string> // fail because it's not an Array
是的!可以使用extends
对泛型类型进行约束。 :
type UnpackedArray<T extends Array<any>> =
T extends (infer U)[] ? U : never;
type T2 = UnpackedArray<string[]>; // string
type T3 = UnpackedArray<string>; // Error: Type 'string' does not satisfy the constraint 'any[]'.
关于typescript - 从 SomeType<T> 中提取类型 T,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56844747/