|
| 1 | +import { Equal, Expect } from "../helpers/type-utils"; |
| 2 | + |
| 3 | +/** |
| 4 | + * Here's a detailed breakdown on why forwardRef doesn't work. |
| 5 | + */ |
| 6 | + |
| 7 | +/** |
| 8 | + * 1. We create a type that represents a function, but with |
| 9 | + * some other attributes. |
| 10 | + */ |
| 11 | +type FuncExpected<Argument> = { |
| 12 | + (arg: Argument): Argument; |
| 13 | + someOtherThing?: string; |
| 14 | +}; |
| 15 | + |
| 16 | +/** |
| 17 | + * 2. We create a function that takes a function as an argument, |
| 18 | + * and infers the position of Argument. |
| 19 | + * |
| 20 | + * This function doesn't do anything at runtime - it just returns |
| 21 | + * the function that was passed in. But it behaves similarly to |
| 22 | + * forwardRef. |
| 23 | + */ |
| 24 | +const forwardRefShim = <Argument>(func: FuncExpected<Argument>) => { |
| 25 | + return (arg: Argument) => func(arg); |
| 26 | +}; |
| 27 | + |
| 28 | +/** |
| 29 | + * 3. We create an identity function, that just takes in an argument |
| 30 | + * and returns it. |
| 31 | + */ |
| 32 | +const identityFunc = <Argument>(arg: Argument) => { |
| 33 | + return arg; |
| 34 | +}; |
| 35 | + |
| 36 | +/** |
| 37 | + * 4. As you can see, when it's not wrapped, identityFunc returns |
| 38 | + * the type that we pass in, 123. |
| 39 | + */ |
| 40 | +const result1 = identityFunc(123); |
| 41 | + |
| 42 | +type test1 = Expect<Equal<typeof result1, 123>>; |
| 43 | + |
| 44 | +/** |
| 45 | + * 5. But when we wrap it in forwardRefShim, it loses its powers |
| 46 | + * of inference! Just like forwardRef. |
| 47 | + */ |
| 48 | +const wrappedIdentityFunc = forwardRefShim(identityFunc); |
| 49 | + |
| 50 | +const result2 = wrappedIdentityFunc(123); |
| 51 | + |
| 52 | +type test2 = Expect<Equal<typeof result2, 123>>; |
| 53 | + |
| 54 | +/** |
| 55 | + * 6. Here's the really crazy part. Go back up to FuncExpected. |
| 56 | + * Comment out the someOtherThing property. |
| 57 | + * |
| 58 | + * It now works! This is because when a function is _just_ a function, |
| 59 | + * TypeScript uses its higher-order function powers on it. But when |
| 60 | + * it has other properties, it doesn't. |
| 61 | + * |
| 62 | + * Bizarre! |
| 63 | + */ |
0 commit comments