Here's a question that is somewhat similar to TypeScript function return type based on input parameter, but with a twist involving promises. The scenario is as follows: if the input is a string, then the method returns a PlaylistEntity, otherwise it returns an array of PlaylistEntity objects.
type TypeName = string | string[]
type ObjectType<T> = Promise<T extends string ? PlaylistEntity : PlaylistEntity[]>
async get<T extends TypeName>(playlists: T): ObjectType<T>{
try {
const col = collection(firestore, 'playlists')
if(Array.isArray(playlists)){
const fetchArray = playlists.slice(0, 10)
const q = query(col, where('__name__', 'in', fetchArray))
const docs = await getDocs(q)
return docs.docs.map(v => {return {id: v.id, ...v.data()} as PlaylistEntity})
}
else{
const docRef = await getDoc(doc(col, playlists))
return {id: docRef.id, ...docRef.data()} as PlaylistEntity
}
}catch (e) {
throw new HttpException(e.message, HttpStatus.INTERNAL_SERVER_ERROR)
}
}
An error message TS2322 pops up saying: "Type 'PlaylistEntity' is not assignable to type 'T extends string ? PlaylistEntity : PlaylistEntity[]'."
This happens at line 43 where we have: return {id: docRef.id, ...docRef.data()} as PlaylistEntity