gpt4 book ai didi

typescript - 是否可以将 typeof 与泛型函数一起使用?

转载 作者:行者123 更新时间:2023-12-04 04:05:18 28 4
gpt4 key购买 nike

是否可以为泛型函数的返回类型设置别名?像这样?

export function ok<TValue>(value: TValue) {
return {
type: 'Ok',
value,
} as const;
}

export type Ok<TValue> = ReturnType<typeof ok<TValue>>;

最佳答案

这是一个有趣的谜题。我相信答案是(有点)是的,但它相当困惑。

根本问题是typeof ok会考虑valueunknown .没有什么好的方法可以得到 type重写声明unknowns所以让我们定义一些类型来为我们做这件事。

// first, one that will visit all the properties in a type (recursively)
type ReplaceUnknownChildren<TIn, TWith> =
{ [K in keyof TIn]: ReplaceUnknown<TIn[K], TWith> };

// second, a type that replace any `unknown` with a specific type
type ReplaceUnknown<T, TWith> = unknown extends T ? TWith : T;

然后我们想要一个 ReturnType<T> 的变体那将为我们做到这一点。我们必须明确提供 T我们想要绑定(bind)(名称需要在范围内),因此语法与您可能期望的有点不同。


type GenericReturn<T, V> =
T extends (...args: any[]) => infer R ?
ReplaceUnknownChildren<R, V> :
any;

把它们放在一起

type ReplaceUnknownChildren<TIn, TWith> =
{ [K in keyof TIn]: ReplaceUnknown<TIn[K], TWith> };

// second, a type that replace any `unknown` with a specific type
type ReplaceUnknown<T, TWith> = unknown extends T ? TWith : T;

type GenericReturn<T, V> =
T extends (...args: any[]) => infer R ?
ReplaceUnknownChildren<R, V> :
any;

export function ok<TValue>(value: TValue) {
return {
type: 'Ok',
value,
} as const;
}


export type Ok<TValue> = GenericReturn<typeof ok, TValue>;

给你这个

inferred type

最大的限制是如果您在函数的返回类型中有多个泛型类型。使用可变泛型类型(在 TypeScript 4.0 中出现)可能可以做到这一点,但我必须尝试使用​​它们才能确定。

关于typescript - 是否可以将 typeof 与泛型函数一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62601870/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com