I'm looking for a way to quickly define the available values/options for a radio group But I can't figure out a way to make it works without some compromises.
My naive approach (but won't work) would ideally be this:
import React from 'react'
type FieldValues = Record<string, unknown>
type Form = {
choices: 'foo' | 'bar' | 'baz'
}
type Radio<T extends {[K in keyof T]: T[K]}> = {
name: K
options?: {label: string, value: T[K]}
}
function Radio<T extends FieldValues>({name, ...props}: Radio<T>) {
return null
}
function App() {
return (
<>
<Radio<Form> name='choices' />
</>
)
}
You define once and for all your form, and you use your name in order to derive the values. But obviously typescript doesn't know what is K here...
My second approach would be this:
https://www.typescriptlang.org/play?#code/JYWwDg9gTgLgBAJQKYEMDG8BmUIjgcilQ3wChSYBPMJOAMWCQBsATANRSYFckBnOALyIkaaCwA8vGFGAA7AOYAaOF1kBrWRADusgHzkqNetDxCA3qThw0ACwjA0fAFwFMECPjgAfAgCMUUJ4++P4AXmQAvgbUtAgoLMAQ4gAqcEgAHjBIsiz8DMzsnDy8ygDSaZnZuXBqSJQQmHDJuoJwFlayKCBILqWWcBBgMImyvAD8LmZMKL7MLlIyCsoAbkU9TQDapQC6UVGkmKoYI4jxiSkVWTl5jKwc3Hxll1X8tfWNzQAUZp3dygB0gLAODAvAiLjiCSSyTKugAlG1+kQYFwoLI4LIuEwmKR9odZMcIOiAIJgMCfBHtODI1Hoz79KzifRWFlwcSQ850EzKfC2eyOXj4Fq-JACXl2Bx8TwAemZLPEsv6cNxQA
But I kind have to repeat myself, so I really don't like it, furthermore, I don't even have autocomplete on the generic part.
I think I'm making this too complicated compared to what it should be but I can't figure out a way to handle this. What am I missing here?
The Playground lets you write TypeScript or JavaScript online in a safe and sharable way.