Last active
June 2, 2020 08:44
-
-
Save janjakubnanista/bc4bb76565ff9f9ddf8a989abdb79f4d to your computer and use it in GitHub Desktop.
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
// Approach 1: the easy way out | |
// | |
// We can just define the return type of our Select | |
// and make sure it matches the return type of React.FC | |
function Select<T>(props: SelectProps<T>): React.ReactElement | null { | |
return null; | |
} | |
// Approach 2: diving back in looking for a better way | |
// | |
// We can create a type that accepts a type parameter | |
// and puts a constraint on it, in our case we will demand | |
// the type parameter to be a React.FC | |
type AssertComponent<C extends React.FC<any>> = C; | |
// Then we use it in our Select component | |
type AssertSelect = AssertComponent<typeof Select>; | |
// Approach 3: the light at the end of the tunnel | |
// | |
// TypeScript 3.7 introduced "assertion signatures" that | |
// allow us to define an assertion function. | |
// We might use such function to ensure that anything we pass to it is a React.FC | |
// while writing no code whatsoever! BINGO! | |
function assertFC<P>(component: React.FC<P>): asserts component is React.FC<P> {} | |
// Then in your Select component | |
assertFC(Select); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment