I'm using GraphQL's dataloader and I'd like to make my return types more strict based on the keys that are passed in. How could I accomplish this? Feeble attempt below. I know why it doesn't work, but not sure what to fix. (same code exists in ts playground here)
type FruitName = 'apple' | 'banana'
type FruitKey<TName extends FruitName> = {name: TName, id: number}
type Apple = 'A'
type Banana = 'B'
interface FruitValues {
apple: Apple
banana: Banana
}
declare class DataLoader<K, V> {
load(key: K): V
}
function getLoader<T extends FruitName>() {
// This doesn't work, but it's the goal-- use the T generic to show the relationship between key & value.
return new DataLoader<FruitKey<T>, FruitValues[T]>()
}
function main() {
const fruitLoader = getLoader()
// Given that the name is 'apple', the return type should be Apple, but it is Apple | Banana
const apple = fruitLoader.load({name: 'apple', id: 1})
// Given that the name is 'banana', the return type should be Banana
const banana = fruitLoader.load({name: 'banana', id: 2})
}