【问题标题】:Get the type of generic function without invoking the function in typescript获取泛型函数的类型而不调用打字稿中的函数
【发布时间】:2019-05-29 23:22:20
【问题描述】:

我有一个这样的通用函数:

function foo<T>(val: T) { return val; }

我有一些类型:

type StringType = string;
type NumType = number;

现在我想引用给定类型的 'foo' 函数,但它不起作用:

const stringFunc = foo<StringType>;
const numFunc = foo<NumType>;

请注意,我不想调用 'foo' 函数,否则,我可以这样做:

const stringFunc = (val: string) => foo<StringType>(val);
const numFunc = (val: number) => foo<NumType>(val);

有可能吗?

【问题讨论】:

标签: function typescript generics


【解决方案1】:

如果您只想强制输入并且不介意额外输入,您可以这样做:

const stringFunc: (val: string) => string = foo;
const numFunc: (val: number) => number = foo;

但目前通常无法将类型参数应用于泛型函数。

【讨论】:

  • 我一直在寻找将类型参数应用于您提到的泛型函数,但您的建议实际上解决了我的问题!谢谢
【解决方案2】:

类型转换或调用其他一些特殊的泛型函数怎么样?

TypeScript REPL

function foo<T>(v: T) { return v }

type UnaryFunction<T> = (v: T) => T


// casting
const asStrFoo = foo as UnaryFunction<string> // asStrFoo(v: string): string
const asNumFoo = foo as UnaryFunction<number> // asNumFoo(v: number): number


// identity function
const bind = <T>(f: UnaryFunction<any>): UnaryFunction<T> => f

const strFoo = bind<string>(foo) // strFoo(v: string): string
const numFoo = bind<number>(foo) // numFoo(v: number): number


// function factory
function hoo<T>() { return function foo(v: T) { return v } }
// function hoo<T>() { return (v: T) => v }

const strHoo = hoo<string>() // strHoo(v: string): string
const numHoo = hoo<number>() // numHoo(v: number): number

注意

// This condition will always return 'false' since the types 'UnaryFunction<string>' and 'UnaryFunction<number>' have no overlap.
console.log(strFoo === numFoo) // true
// This condition will always return 'false' since the types 'UnaryFunction<string>' and 'UnaryFunction<number>' have no overlap.
console.log(asStrFoo === asNumFoo) // true
// This condition will always return 'false' since the types '(v: string) => string' and '(v: number) => number' have no overlap.
console.log(strHoo === numHoo) // false

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-07-08
    • 2023-02-22
    • 1970-01-01
    • 2019-07-05
    • 2020-03-22
    • 2021-04-10
    • 2017-12-14
    • 2020-05-09
    相关资源
    最近更新 更多