我為工廠函式定義了一個型別,其中回傳的函式之一使用泛型。
type Factory = (param: string) => {
func: <T extends {}>(param: string) => Promise<T>,
};
const factory: Factory = __factoryParam => ({
func: async <T>(__param) => {
return Promise.resolve({} as T);
},
});
當我將滑鼠懸停在__param上面代碼中的引數上時,我得到錯誤Parameter '__param' implicitly has an 'any' type.ts(7006)。
如果我擺脫了泛型,則__param輸入正確。如果我在實作中顯式鍵入引數,它當然可以作業:
func: async <T>(__param: string) => {
我在這里做錯了什么?
uj5u.com熱心網友回復:
在這種情況下,可以as any在回傳值上使用并在實作中省略泛型:
TS游樂場
type Factory = (param: string) => {
func: <T extends {}>(param: string) => Promise<T>,
};
const factory: Factory = __factoryParam => ({
async func (__param) {
return Promise.resolve({}) as any;
},
});
const result = factory('str').func<{msg: 'hello'}>('str2'); // Promise<{ msg: 'hello' }>
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/415126.html
標籤:
