I'm attempting to determine the return type of getAllRaces()
as () => Race[]
.
Here is what I have tried so far:
type CollectionMap = {
races: Race[]
horses: Horse[]
}
type Race = {
date: Date
}
type Horse = {
name: string
}
type UnionizeKeys<T> = {
[k in keyof T]: k
}[keyof T]
type CollectionName = UnionizeKeys<CollectionMap> // "races" | "horses"
// Unsuccessful attempts
const getAll1 = (name: CollectionName) => [] as CollectionMap[name];
// 💥 Type 'name' cannot be used as an index type.(2538)
const getAll2 = (name: CollectionName) => [] as CollectionMap[typeof name as const];
// 💥 A 'const' assertions can only be applied to references to enum members,
// or string, number, boolean, array, or object literals.(1355)
const getAll = (name: CollectionName) => [] as CollectionMap[typeof name];
const getAllRaces = () => getAll('races')
// ❌ const getAllRaces: () => Race[] | Horse[]
// ✅ const getAllRaces: () => Race[]
TypeScript Playground
Thank you for your assistance.