Created
March 24, 2022 10:52
A cheat sheet to React with TypeScript, on how to extend props with props from the usage scope.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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