How to create a type-safe generic component? #1627
Unanswered
virtuallyunknown
asked this question in
Q&A
Replies: 1 comment
-
@virtuallyunknown There's some ideas being thrown around with branding components in #1606 , but it's a draft for now. To get this feature to work now, // select-menu.tsx
type SelectOption<T> = {
text: string;
value: T
}
type SelectFieldProps<T extends string> = {
// we don't care about the whole field, we only want the value as generic reference
field: {
state: {
value: T
}
},
label: string;
// NoInfer ensures that you can't 'cheat' the system by TypeScript inferring T from the provided options.
// You only want the field to be the source of truth.
options: NoInfer<SelectOption<T>[]>
}
// main.tsx
<field.SelectField label="type" field={field} options={[
{ text: 'Dog', value: 'dog' },
{ text: 'Cat', value: 'cat' },
// Error! not assignable to 'cat' | 'dog' | 'bird'
{ text: 'Bird', value: 'invalid' }
]} |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
Let's say we have the usual form composition in place:
And then we want to define a reusable and type-safe
SelectField
component. A "naive" component, for the lack of a better word would look like this:This of course would work, but there is no type-safety at a form-level.
You can see that I am able to pass any
options
I want to mySelectField
component, because theSelectOptions
property accepts an array of objects withtext
andvalue
of typestring
.This could in theory be solved if we used generic parameters for the
SelectField
:This is just pseudo-code, but it illustrates what I'm trying to achieve. If it worked, then in my example
<field.SelectField ...>
the options you would be able to pass would be constrained to options that are of a valid type only. Otherwise Typescript will throw an error (which is what we want).Is it possible to achieve this?
Beta Was this translation helpful? Give feedback.
All reactions