This code snippet showcases a function that can recognize that the key "banana" cannot have the value "red":
type Fruits = {
banana: 'yellow' | 'green'
strawberry: 'red'
}
const fruit = <K extends keyof Fruits>(module: K, action: Fruits[K]) => true
fruit('banana', 'red') // error: not assignable to parameter of type '"yellow" | "green"
Is there a way to achieve similar functionality using tuples?
type FruitTuple<K extends keyof Fruits> = [K, Fruits[K]]
const c: FruitTuple<keyof Fruits> = ['banana', 'red'] // no error
What about using template literals?
type FruitTemplate<K extends keyof Fruits> = `${K}.${Fruits[K]}`
const c: FruitTemplate<keyof Fruits> = 'banana.red' // no error
Can this also be done with objects?
type Fruit<K extends keyof Fruits> = {
name: K
color: Fruits[K]
}
const d: Fruit<keyof Fruits> = { name: 'banana', color: 'red' } // no error