Home > OS >  Force two type union keys to be the same type
Force two type union keys to be the same type

Time:08-13

I am creating a Props type like this:

type Props = {
  currentValue: number | string | Array<string> | undefined;
  newValue: number | string | Array<string> | undefined;
  ... // other props
}

How can I enforce that both keys are the same type?

CodePudding user response:

You can combine the type utility Record<Keys, Type> with a generic type parameter.

Then, just intersect (&) that type with your "other props":

TS Playground

type CurrentAndNewValue<T> = Record<'currentValue' | 'newValue', T>;

type Props = CurrentAndNewValue<number | string | Array<string> | undefined> & { exampleProp: string };

declare const props: Props;

props.currentValue
    //^? (property) currentValue: string | number | string[] | undefined
props.newValue
    //^? (property) newValue: string | number | string[] | undefined
props.exampleProp
    //^? (property) exampleProp: string

Or, without the intermediate utility type:

type Props = Record<'currentValue' | 'newValue', number | string | Array<string> | undefined> & { exampleProp: string };
  • Related