In my current project, I am in the process of developing a versatile hook that interfaces with Firebase/Firestore to retrieve all items from a specified collection. To ensure the correct types for the returned items, I have created an interface called ICollectionMap
which outlines the structure of the data. This is an overview of what I have implemented so far:
export const useCollection = <TCollectionMap extends Record<string, any>>(
collectionName: keyof TCollectionMap
): {
collection: TCollectionMap[keyof TCollectionMap]
} => {
const [collection, setCollection] = useState<TCollectionMap[keyof TCollectionMap]>([])
useEffect(() => {
// fetching data from Firebase will go here
...
const data = ...
setCollection(data)
}, [])
return { collection }
}
For example, let's consider the following type definitions:
interface INames { name: string }
interface IAges { age: number }
interface ICollectionMap {
names: INames[]
ages: IAges[]
}
When utilizing the hook like this:
const { collection } = useCollection<ICollectionMap>('names')
I expected the type of collection
to be INames[]
, however TypeScript indicates that it could also be INames[] | IAges[]
. Is there a way to address this issue effectively within TypeScript?