[英]How to get parameter types of a generic function with instantiated generic type parameters?
我的目標是將泛型類型 function 的Parameter
類型提取為我以后可以使用的新泛型類型:
// we have a given function like this:
function genericFunction<T>(a: T) {
return a;
}
type genericParamsType = Parameters<typeof genericFunction>; // this will resolve to a type of [unknown]
// I would like to achieve something like this:
// type genericParamsType<PassDownType> = Parameters<typeof genericFunction<PassDownType>>;
// but that is a syntax error
// if it would work, I could the following:
// const newparams: genericParamsType<string> = ["hello"] // correct
// const newparams2: genericParamsType<number> = ["hello"] // error because its not a string
TypeScript 4.7 引入了實例化表達式,所以你原來的想法不再是語法錯誤。 實例化表達式允許使用泛型類型參數的具體類型來實例化泛型函數。
因此, genericParamsType
可以寫成如下:
type genericParamsType<T> = Parameters<typeof genericFunction<T>>;
雖然這仍然不允許真正通用的解決方案,因為仍然必須在具體實現上使用typeof
類型查詢,但足以涵蓋問題中概述的用例:
// we have a given function like this:
function genericFunction<T>(a: T) {
return a;
}
type genericParamsType<T> = Parameters<typeof genericFunction<T>>;
const newparams: genericParamsType<string> = ["hello"] // OK
const newparams2: genericParamsType<number> = ["hello"] // Type 'string' is not assignable to type 'number'.
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.