我有一個從 Firebase 中的資料庫獲取所有檔案的函式該函式本身可用于檢索任何型別的檔案,這就是為什么我需要用泛型指定它回傳的任何內容。
我現在這樣做:
export const getAllDocuments = async <DocType>(collectionName: string) => {
const documents: DocType[] = [];
const querySnapshot = await getDocs(collection(db, collectionName));
querySnapshot.forEach((doc) => {
documents.push({
id: doc.id,
...doc.data(),
});
});
return documents;
};
但是我收到了這個錯誤:“TS2345:'{id:string;}'型別的引數不可分配給'DocType'型別的引數。'DocType'可以用與'{id:無關的任意型別實體化:細繩; }'” ??
我像這樣呼叫函式:
const documents = await getAllDocuments<ExerciseDocument>('exercises');
我在這里做錯了什么?:)
見這里的測驗例子:https://www.typescriptlang.org/play?target=8&jsx=0#code/MYewdgzgLgBAhgJwXAnjAvDA2gWAFAwwDe hhAlgCYBcMAjKTAL4A0jJBZVtATI0-gC6 fKEiwA5gFMoAQQA28gCIhgAVwC2UsFAgZ4EFGGAwAPABUAfAApEE2tATkwEgJQZLxRmOgxKqzW1dWnMsQX0wgG5GRGQUADoAMxAEAFE4YAALa2t3dE8OMj8ArR0IeIAHNQhswqKYbhgAcjoeAGYmxkImV2jOHr7GBBk1BDBi9VLdPqZBvCA
uj5u.com熱心網友回復:
你可以試試
const getAllDocuments = async <T extends { id: string }>(arg: string) => {
const documents: T[] = [];
array.forEach(() => {
documents.push({
id: '123'
} as T);
});
return documents;
};
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/405755.html
標籤:
上一篇:從類串列陣列中獲取型別
