我有两种类型:(() => any) |未定义
和() => 任何
。我想提取函数的返回类型,但前提是该值绝对不是未定义的。
我尝试过以下方法:
type IsUndefined<T> = T extends (() => any) ? "no" : "yes";
但这解析为“yes” |当类型未定义时为“no”
。我想在不创建联合的情况下检测这些类型之间的差异。
请参阅this playground link举个例子。
这是短篇故事,长篇故事是我有一个如下所示的结构:
type MyStruct = {
optionalHook?: ((...args: any) => any) | undefined,
requiredHook: (...args: any) => any,
}
我想提取可选钩子(Hook)的返回类型,但仅限于它存在时。否则我想提取所需 Hook 的返回类型。
参见this playground link以获得更全面的示例。
最佳答案
不知道为什么缺少 optionalHook
不会将 T
推断为 createStruct
中的 undefined
但我'通过添加默认通用参数,我们设法获得了所需的结果:
// Create the generic struct
type MyStruct<T extends ((...args: any) => any) | undefined, U extends (...args: any) => any> = {
optionalHook?: T,
requiredHook: U,
}
// Utility function for easily creating stucts with the correct type.
// Without this I'd have to type the generic arguments manually for every struct instance.
function createStruct<T extends ((...args: any) => any) | undefined = undefined, U extends (...args: any) => any = (...args: any) => any>(struct: MyStruct<T, U>) {
return struct;
}
const withOptional = createStruct({
optionalHook: () => 5,
requiredHook: () => "hello",
});
const withoutOptional = createStruct({
requiredHook: () => true,
});
// The function for extracting the return type
type getReturnType<T> =
T extends MyStruct<infer O, infer R> ?
O extends (...args: any) => infer OR ?
OR :
R extends (...args: any) => infer RR ? RR : never :
never;
type ResultWithOptional = getReturnType<typeof withOptional>;
type ResultWithoutOptional = getReturnType<typeof withoutOptional>;
将 optionHook
显式设置为 undefined
也可以:
关于typescript - 如何在 TypeScript 中区分 `(() => any) | undefined` 和 `() => any`?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70597493/