Description
π Search Terms
"assert function", "react hook", "Assertions require every name in the call target to be declared with an explicit type annotation", "2775"
π Version & Regression Information
- This is the behavior in every version I tried
β― Playground Link
π» Code
import React from "react";
function invariantFn(condition: unknown, message: string): asserts condition {
if (!condition) {
throw new Error(message);
}
}
function useInvariant() {
return invariantFn;
}
type Filter = {
title: string;
} | null;
function Test1({ filter }: { filter: Filter }) {
// using the hook version doesn't work, even if I return exactly the same function
const invariant = useInvariant();
invariant(filter, "Filter necessary");
console.log(filter.title);
// explicitly typing the hook version works? WAT
const invariant2: ReturnType<typeof useInvariant> = useInvariant();
invariant2(filter, "Filter necessary");
console.log(filter.title);
return <div>{filter.title}</div>;
}
function Test2({ filter }: { filter: Filter }) {
// calling the funciton directly works fine
invariantFn(filter, "Filter necessary");
console.log(filter.title);
return <div>{filter.title}</div>;
}
π Actual behavior
I need to manually type the function returned from my hook, even though it is the same exact function used without needing a type.
π Expected behavior
TypeScript should allow me to return an assert function from a hook or other function and not need to manually type it at the callee location.
Additional information about the issue
I'm trying to create an invariant
function that will act similar to the npm invariant package. I'd like to put it into a React hook so that I can use another hook to grab our logger, and then return a function that will call the invariant
function and our logger.
Even with this slimmed down example that I provided, without any of the logging logic, TS is unhappy and forces me to provide some type annotation for every consumer of the hook.