I need help implementing a specific function type:
type TestType<T extends HTMLElement> = (input: T) => React.Ref<T>;
I have a variable that I want to be typed with the above type for strict type guarantees on the return type:
const Test = (input) => {
return React.useRef(input);
}
I'm struggling to apply this type to the variable Test
.
Here are some approaches I've attempted:
- Being as explicit as possible:
export const Test: TestType<T extends HTMLElement> = <K extends HTMLElement>(input: K) => {
return React.useRef<K>(input);
}
This fails during compilation with various errors, one being
"Cannot find name 'T'."
- Letting Type Inference guide me
export const Test: TestType = (input: K) => {
return React.useRef(input);
}
- This attempt also fails because
TestType
requires a type argument
After reviewing TypeScript documentation, I came across a similar example:
interface GenericIdentityFn {
<T>(arg: T): T;
}
function identity<T>(arg: T): T {
return arg;
}
let myIdentity: GenericIdentityFn = identity
However, I couldn't find a way to pass type information to the variable declaration and let TypeScript infer the type of the function argument (input
) or the return type. Although in this case, it's straightforward for TS to infer from the implementation.
Is there a solution to this issue?