簡體   English   中英

獲取通用函數的類型,而無需在打字稿中調用該函數

[英]Get the type of generic function without invoking the function in typescript

我有一個像這樣的通用函數:

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);

可能嗎?

如果您只想強制鍵入而又不介意額外鍵入,則可以這樣操作:

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

但目前尚無法將類型參數應用於通用函數。

如何進行類型轉換或調用其他一些自組織通用函數?

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM