I'm trying to build a generic React component which allows number, string, or Date values. I want users of the component to be able to define a callback when the value is updated, and to allow for that callback to define the value as either a number, string, or Date.
Here's a watered-down example of what I'm trying to do overall (I'm aware that this specific example could be fixed by forcing value
to always be a string
but that's not the purpose of this question):
import React from 'react';
// Union Type
type ValueType = number | string | Date;
// Generic Component
interface InputProps {
value: ValueType;
onChange: (value: ValueType) => void; // <-- need to change this signature to.. something
}
const Input = ({ value, onChange }: InputProps) => (
<input value={value.toString()} onChange={(e) => onChange(e.target.value)} />
);
// Implementation of Generic Component
interface TestProps {
onInputUpdate: (value: string) => void;
}
const Test = ({ onInputUpdate }: TestProps) => (
<Input
value="test"
onChange={(e: string) => onInputUpdate(e)} // <-- 'number' is not assignable to 'string'
/>
);
export default Test;
I understand why this doesn't work, but I'm not sure how to make it work the way I want it to.
I've also tried using generics i.e. onChange: <T extends ValueType>(value: T) => void
with similar results.
There are two ways I know I can "fix" it, but I'd like to avoid them if possible:
- Making the signature
onChange: (value: any) => void
- Forcing users to use the
ValueType
type when implementing their callback
Thanks in advance for your help!
Edit: onChange: (value: any) => void
can allow the function to be implemented as onChange: (value: string) => {}
, is there a way to do this but restrict it to being types which are part of ValueType
instead of any
?
T
frome.target.value
(which is always astring
in your example)? You can fix it withinterface InputProps<T extends ValueTypes>
and usingT
in the field definitions, but then you run into the problem thatInput
must be ofInputProps<string>
as you've written in now.value
to always be exactly one ofstring
,number
, orDate
? Never more specifc (literal types like"a"
) or more wide (unions likestring | number
)?value
is coming from a callback in a child component's prop via useContext, which can benumber | string | Date
.value
to be more specific or wider than any single type, as long as the type ofvalue
is contained withinValueType
. But what you provided is definitely a good start.