Skip to content

Returned assert functions need needlessly explicitly typedΒ #56695

Closed
@jas7457

Description

@jas7457

πŸ”Ž 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

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Design LimitationConstraints of the existing architecture prevent this from being fixed

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions