Home > Software design >  Can a dynamic type function param be extended?
Can a dynamic type function param be extended?

Time:04-06

Is this a possibility (and if so how)?

type extendedValues = { name: string };

type Props<T> {
  values: T & extendedValues ?
}

const ReactFuncComponent = <T extends Props<T>>({ values }: Props<T>) => {
...
}

So essentially I want to say you can pass in an object that contains any fields with any values but it must also include a name of type string:

<ReactFuncComponent values={{ age: 0, name: '' }} />

CodePudding user response:

If I understood your question correctly, you can achieve what you want in following way:

interface Credentials {
  name: string;
}

type ExtendedValues<T> = Credentials & T;

type Props<T> = {
   value: ExtendedValues<T>
}

const TestComponent = <T, >(props: Props<T>) => {
  return <p>Some text here</p>
};

// Example of usage

<TestComponent value={{name: "Name"}} /> // Will be OK
<TestComponent value={{name: "Name", age: 25}} /> // Will be OK
<TestComponent value={{age: 25}} /> // Error: property 'name' is missing

  • Related