簡體   English   中英

具有特定泛型類型參數的泛型 function 的參數類型,在 typescript

[英]Parameters type of a generic function with specific generic type argument, in typescript

在第三方 package 中考慮以下代碼:

// A third-party package
type InternalComplexType<T> = ...; // not exported
export function foo<T>(arg1: T, arg2: InternalComplexType<T>): void {}

例如,如何獲取InternalComplexType<number>

這失敗了:

type SecondArgType = Parameters<typeof foo<number>>[1]; // syntax error

typescript游樂場

因此,實現此目的的最佳方法是通過接口 function 定義更改 function 定義,以便它與 typescript 實用程序類型一起使用。 目前,使用 typescript 編譯器執行typeof func並嘗試在typeof中傳遞泛型將不起作用。 因此錯誤。

你可以這樣做:

type InternalComplexType<T> = T | number;
export function foo<T>(arg1: T, arg2: InternalComplexType<T>): void {}

// create an interface type for you generic function
interface foo<T>{
   (arg1: T, arg2: InternalComplexType<T>): T
}

type SecondArgType = Parameters<foo<number>>[1];

暫無
暫無

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

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