Home > OS >  Define a Typescript Interface Value as either a set of strings or whatever was passed as an argument
Define a Typescript Interface Value as either a set of strings or whatever was passed as an argument

Time:02-17

I am not sure if I phrased the question title correctly - I am working on react components in a library that have a certain set of predefined values for some of the properties. But on a per usage basis, additional values need to be added to the interface. This works well so far:

export interface CompProps<Variant = string> {
  variant?: 'banana' | 'strawberry' | Variant;
}

I noticed though, that when working with the component, it will now accept any string for the variant property and the IDE will also not suggest these predefined values under certain circumstances.

What is the proper way to go about this?

CodePudding user response:

Perhaps you could take advantage of the default type parameter to type the variant property more strongly, since it is currently 'banana' | 'strawberry' | string by default.

If you set the default parameter to never instead, you could avoid union with the general string, effectively enforcing variant to be either 'banana' or 'strawberry', which should give the IDE a stronger hint about the desired value. Here I've also added a constraint such that the variant is a string, which I assume is what you want.

If one were to set the Variant type parameter, they could explicitly state which strings they expect to pass like so:

export interface CompProps<Variant extends string = never> {
  variant?: 'banana' | 'strawberry' | Variant;
}

const test: CompProps<'chocolate'> = {variant: 'chocolate'};

With this solution however, the component will still have to accommodate the most general type (i.e. CompProps), so it most likely won't be very beneficial if the predefined values need to be apparent within the component.

  • Related