我正在嘗試創建一個泛型,它將為我提供有關所有類方法回傳型別的資訊( 欄位,但它們并不那么重要)。
假設我創建了這樣一個類:
class TestClass {
testField: string;
constructor() {
this.testField = 'test';
}
testMethod1(param: number): number {
return param;
}
testMethod2(param: string): string {
return param;
}
}
結果,我想要這樣的型別:
interface TestClassMethodsNamesReturnType {
testMethod1: number;
testMethod2: string;
}
到目前為止我嘗試過的
映射型別 型別推斷:
示例 1
export type ClassMethodsNamesReturnType<T extends Function> = { [k in keyof T['prototype']]: ReturnType<T['prototype'][k]>; } const x: ClassMethodsNamesReturnType<TestClass> = { //... }錯誤:
“TestClass”型別缺少“Function”型別的以下屬性:apply、call、bind、prototype 和另外 5 個
映射型別并將類視為物件:
示例 2
// I think here I can have problems to decide is the key of my class is a field or method // what can be a problematic to decide what I should use (typeof T[K] or ReturnType<typeof T[K]>) export type ClassMethodsNamesReturnType<T extends Record<string, T[K]>, K extends keyof T> = { [K]: T[K]; }錯誤:
型別文字中的計算屬性名稱必須參考其型別為文字型別或“唯一符號”型別的運算式
'K' 僅指一種型別,但在這里用作值
你有什么提示或想法我該如何實作這一目標?
uj5u.com熱心網友回復:
您可以通過映射型別執行此操作,盡管您需要使用as映射型別中的子句進行條件過濾。然后,檢查該值是否擴展Function,如果沒有則回傳never,這樣它就不會被映射。這是完整的代碼:
class TestClass {
testField: string;
constructor() {
this.testField = 'test';
}
testMethod1(param: number): number {
return param;
}
testMethod2(param: string): string {
return param;
}
}
type FnReturns<T> = { [K in keyof T as T[K] extends Function ? K : never]: ReturnType<T[K] extends (...args: any[]) => any ? T[K] : never> };
// Correctly passes:
const foo: FnReturns<InstanceType<typeof TestClass>> = {
testMethod1: 23,
testMethod2: "hey",
}
// correctly fails:
const fail: FnReturns<InstanceType<typeof TestClass>> = {}
TypeScript Playground 鏈接
還要注意我如何使用InstanceType來typeof TestClass獲取 的實體方法和屬性TestClass。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/441393.html
上一篇:我的基本測驗軟體中的串列有問題
