简短的回答是,TS4有一个PR.7用于此功能.与你的问题特别相关...
type Box<T> = ReturnType<typeof makeBox<T>>; // { value: T }
这与#37181的解决方案非常接近.它会允许我们做...
return { value }; };
// Can we do it or something similar? Currently doesn't compile :(
type MakeBox<T> = ReturnType<typeof makeBox<T>>
// As it now allows us to do (no generics though)
const stringMakeBox = makeBox<string>; type MakeBox = ReturnType<typeof stringMakeBox>
// And even more relevant to support generics if we can now do: type
MakeBox = ReturnType<typeof makeBox<string>>
是的,您确实可以使用该模式来捕获泛型函数的泛型返回类型.这是以前不可能的.我将更新PR描述以包含一个示例.
Comment here
我找不到任何关于它是对函数的类型别名有效,还是只对运行时函数有效(用typeof
推断),但您可能只需要使用实际的运行时实现,并根据需要使用typeof
这是在nightly build上的工作,注意你仍然需要一个运行时实现,不管它是否真的实现了任何东西都取决于你,它可能是一些不返回任何东西的模拟函数
type FooFormatter = <S extends string>(input: S) => `foo-${S}`;
const FooFormatterImplementation: FooFormatter = {} as any; //mock implementation
type StringFormatter = <S extends string>(input: S, ...args: never) => string;
type foo = ReturnType<typeof FooFormatterImplementation<"hey">>
// ^? `type foo = "foo-hey"`
My two-cents and more (More Post Script stuff)
我强烈建议调查他们type-fest
岁以上的一些类型,如果你还没有的话.尤其地
通过阅读库,你似乎对类型有了很好的了解,我认为你可能实际上受到了Deno的TS版本的限制.
有很多变通方法,但我不确定它们是否真的适用于您的用例.
编辑:使用声明合并和接口的变通方法
This is not dependent upon TS4.7万岁!
type FooFormatter = <S extends string>(input: S) => `foo-${S}`;
type BarFormatter = <S extends string>(input: S) => `bar-${S}`
export interface Formatters {
FooFormatter: FooFormatter,
BarFormatter: BarFormatter
}
// then anyone wanting to add a custom formatter, has to modify and reexport the interface,
// this is similiarly done in @react-mui, using module augmentation
// https://www.typescriptlang.org/docs/handbook/declaration-merging.html
function takeInnerTest<T extends string, FmtKey extends keyof Formatters>(input: T, formatter: FmtKey)
{
type formattersDiscriminated = {
[K in keyof Formatters]: Formatters[K]
}[FmtKey]
const __mockFunction: formattersDiscriminated = ((...args: any[]) => undefined) as any
const __mockReturn = __mockFunction(input)
type String = ReturnType<typeof __mockFunction>
type ReturnValue = Extract<typeof __mockReturn, String>
return null! as ReturnValue
}
const foo3 = takeInnerTest("hey", "FooFormatter")
type foo3 = typeof foo3
// ^?
const foo4 = takeInnerTest("hey", "BarFormatter")
type foo4 = typeof foo4
// ^?
TS Playground