Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save KrzysztofZawisla/3bd2c19e727155f38528d7356b69c217 to your computer and use it in GitHub Desktop.
Save KrzysztofZawisla/3bd2c19e727155f38528d7356b69c217 to your computer and use it in GitHub Desktop.
A cheat sheet to React with TypeScript, on how to extend props with props from the usage scope.
type ComponentWithGenericPropertiesBaseWithoutGeneric = {
baseValue: string;
};
type ComponentWithGenericPropertiesBase<T> = T extends infer T
? T & ComponentWithGenericPropertiesBaseWithoutGeneric
: ComponentWithGenericPropertiesBaseWithoutGeneric;
type ComponentWithGenericPropertiesFirstUnion = {
valueFromFirstUnion: string;
secondValueFromFirstUnion?: string;
valueFromSecondUnion?: never;
secondValueFromSecondUnion?: never;
};
type ComponentWithGenericPropertiesSecondUnion = {
valueFromFirstUnion?: never;
secondValueFromFirstUnion?: never;
valueFromSecondUnion: string;
secondValueFromSecondUnion?: string;
};
type ComponentWithGenericProperties<T> = ComponentWithGenericPropertiesBase<T> &
(
| ComponentWithGenericPropertiesFirstUnion
| ComponentWithGenericPropertiesSecondUnion
);
const ComponentWithGeneric = <T extends object>({
baseValue,
valueFromFirstUnion,
secondValueFromFirstUnion,
valueFromSecondUnion,
secondValueFromSecondUnion,
}: ComponentWithGenericProperties<T>) => {
return <></>;
};
const ComponentToPerformTests = () => {
return (
<>
<ComponentWithGeneric<{ exampleAnotherProperty: string }>
exampleAnotherProperty=""
baseValue=""
valueFromFirstUnion=""
/>
<ComponentWithGeneric<{ test: string }>
test=""
baseValue=""
valueFromFirstUnion=""
/>
<ComponentWithGeneric baseValue="" valueFromFirstUnion="" />
</>
);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment