1

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?

4
  • How do you go about getting a T from e.target.value (which is always a string in your example)? You can fix it with interface InputProps<T extends ValueTypes> and using T in the field definitions, but then you run into the problem that Input must be of InputProps<string> as you've written in now. Feb 11, 2021 at 21:31
  • 1
    Does this work for you? You want value to always be exactly one of string, number, or Date? Never more specifc (literal types like "a") or more wide (unions like string | number)?
    – jcalz
    Feb 11, 2021 at 21:38
  • In my actual code, value is coming from a callback in a child component's prop via useContext, which can be number | string | Date.
    – twhitcomb
    Feb 11, 2021 at 21:39
  • @jcalz, it would technically be possible for value to be more specific or wider than any single type, as long as the type of value is contained within ValueType. But what you provided is definitely a good start.
    – twhitcomb
    Feb 11, 2021 at 21:42

4 Answers 4

2

Another approach here instead of generics is to represent InputProps as a union of three different object types; one member for string values, one for number values, and one for Date values:

type InputProps = {
    value: string;
    onChange: (value: string) => void;
} | {
    value: number;
    onChange: (value: number) => void;
} | {
    value: Date;
    onChange: (value: Date) => void;
}

You can generate this union programmatically from ValueType by distributing your original definition across the ValueType union:

type InputProps = ValueType extends infer T ?
    T extends unknown ? { value: T, onChange: (value: T) => void } : never : never;

Now you will be able to use Input the way you expected to:

const Test = ({ onInputUpdate }: TestProps) => (
    <Input
        value="test"
        onChange={(e: string) => onInputUpdate(e)}
    />
);

with a caveat here that the compiler apparently wants to see the parameter to onChange annotated (e above); if you leave it off it fails to infer the type and falls back to any.

Also, the compiler is unlikely to be able to verify safety of the implementation of Input. This is because the correlation between value and onChange will be lost when you destructure it, so I'd use a type assertion there:

const Input = ({ value, onChange }: InputProps) => (
    <input
        value={value.toString()}
        onChange={(e) => (onChange as (value: ValueType) => void)(e.target.value)}
    />
);

This may not be the best thing for your use case, but I wanted folks who come here to be aware of this possibility too.

Playground link to code

1

I think you are looking for smth like that:

import React from 'react';

// Union Type
type ValueType = number | string | Date;

// Generic Component
interface InputProps<T extends ValueType> {
  value: T;
  onChange: <U=T>(value: U) => void;  // <-- need to change this signature to.. something
}
const Input = <T extends ValueType>({ value, onChange }: InputProps<T>) => (
  <input value={value.toString()} onChange={(e) => onChange(e.target.value)} />
);

// Implementation of Generic Component
interface TestProps<T extends ValueType> {
  onInputUpdate: <U = T>(value: U) => void;
}
const Test = <T extends ValueType>({ onInputUpdate }: TestProps<T>) => (
  <Input<number>
    value={2}
    onChange={(e) => onInputUpdate(e)}  // ok, e is number
  />
);

const Test2 = <T extends ValueType>({ onInputUpdate }: TestProps<T>) => (
  <Input<string>
    value="Hello"
    onChange={(e) => onInputUpdate(e)}  // ok, e is string
  />
);

const Test3 = <T extends ValueType>({ onInputUpdate }: TestProps<T>) => (
  <Input<Date>
    value={new Date()}
    onChange={(e) => onInputUpdate(e)}  // ok, e is Date
  />
);

export default Test;

Playground

There is one drawback: if you provide generic parameter for onInputUpdate it can broke the types. For example:


const Test3 = <T extends ValueType>({ onInputUpdate }: TestProps<T>) => (
  <Input<Date>
    value={new Date()}
    onChange={(e) => onInputUpdate<string>(e)}  // e is string instead of expected Date
  />
);

SECOND APPROACH

import React from 'react';

// Union Type
type ValueType = number | string | Date;

// Generic Component
interface InputProps<T extends ValueType> {
  value: T;
  onChange: <U=T>(value: U) => void;  // 
}
const Input = <T extends ValueType>({ value, onChange }: InputProps<T>) => (
  <input value={value.toString()} onChange={(e) => onChange(e.target.value)} />
);

// Implementation of Generic Component
interface TestProps {
  onInputUpdate: <U>(value: U) => void;
}

const Test = ({ onInputUpdate }: TestProps) => (
  <Input
    value={2}
    onChange={(e) => onInputUpdate(e)}  // ok, e is literal 2
  />
);

const Test2 = ({ onInputUpdate }: TestProps) => (
  <Input
    value={'2'}
    onChange={(e) => onInputUpdate(e)}  // ok, e is literal "2"
  />
);

const Test3 = ({ onInputUpdate }: TestProps) => (
  <Input
    value={new Date()}
    onChange={(e) => onInputUpdate(e)}  // ok, e is Date
  />
);


const Test4 = ({ onInputUpdate }: TestProps) => (
  <Input
    value={['1']} // error, it hsould be ValueType
    onChange={(e) => onInputUpdate(e)}  // ok, e is Date
  />
);
export default Test;

4
  • I tried going down this route too; it may end up being what I do in the end, but all of the generics make things a little messy, especially when the Test component is dealing with more than just one Input component.
    – twhitcomb
    Feb 11, 2021 at 22:06
  • @twhitcomb could you please provice an example where exactly you have an issue with my code? I will try to handle it Feb 11, 2021 at 22:09
  • I'd prefer for users (i.e. those who'd be implementing the Test components in this example) to not have to refer to ValueType directly; I'd rather TypeScript be able to determine if the type the user used for value as an argument to onChange is part of ValueType by defining it in the InputProps interface. It's very possible that what I'm asking isn't possible in TypeScript though, in which case I'll probably implement something similar to what you've suggested.
    – twhitcomb
    Feb 11, 2021 at 22:18
  • @twhitcomb I made an update, please take a look Feb 11, 2021 at 22:56
0

Define the interface like this:

interface InputProps<T extends ValueType> {
    value:T,
    onChange: ((value: T) => void);
}

Although I may have misunderstood you - if value can vary over any of those types at run-time, you would instead have to do a type test in the handler I think.

0

After some research, this has to do with strictFunctionTypes:

interface InputProps {
  value: ValueType;
  onChange(value: ValueType): void;  // onChange declared as a method (does what I expect)

  // onChange: (value: ValueType) => void;  // onChange declared as a property (strict)
}
2
  • 1
    Oh, uh, you could do this, but then nothing will complain if you write value="test" onChange={(e: number) => e.toFixed(2)}. Is that what you want?
    – jcalz
    Feb 12, 2021 at 1:31
  • That's definitely a good point; and the only way around that would be to use generics. But I think that's a separate issue I have to figure out.
    – twhitcomb
    Feb 12, 2021 at 1:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.