I am currently working on a function that accepts an object of keys with values that have specific types. The type for one field is determined by the type of another field in the same object. Here is the code:
// Consider this Alpha type and echo function...
type NoInfer<T> = [T][T extends unknown ? 0 : never]
interface Alpha<Foo extends string> {
foo: Foo
bar: `Depends on ${NoInfer<Foo>}`
}
declare const echo: <T extends string>(x: Alpha<T>) => void
echo({ foo: 'beta', bar: 'Depends on beta'})
// @ts-expect-error Trailing 2 is wrong
echo({ foo: 'beta', bar: 'Depends on beta 2'})
// Now we need a function (bravo) that takes a keyed index of Alphas...
declare const bravo: <T extends { [k: string]: Alpha<string> }>(xs: T) => void
bravo({
one: { foo: `1`, bar: `Depends on 1` },
// @ts-expect-error 1 !== 1x <-- fails
oneX: { foo: `1x`, bar: `Depends on 1` },
two: { foo: `2`, bar: `Depends on 2` },
// @ts-expect-error 2 !== 2x <-- fails
twoX: { foo: `2x`, bar: `Depends on 2` },
})
// How can I make this work?
As indicated by the "fails" comments, while I can get Alpha to work initially, I encounter difficulties with more complex objects of Alphas. Can you assist me in resolving this issue? Thank you!