TypeScript asserts that the Function is not callable

There seems to be an issue with TypeScript not recognizing that a function of type Function is not callable.

type Constructable = { new(...args: any[]): any }

function isClass(func: any) {
  return (
    typeof func === 'function' &&
    /^class\s/.test(Function.prototype.toString.call(func))
  )
}

function coerceOne(data: any, fn: Function | Constructable) {
  if (isClass(fn)) {
    const constructor = fn as Constructable
    return new constructor(data)
  } else {
    return fn(data) // <-- ERROR
  }
}

Error:

This expression is not callable.
  No constituent of type 'Function | Constructable' is callable.(2349)

https://www.typescriptlang.org/play?ssl=14&ssc=11&pln=14&pc=6#code/C4TwDgpgBAwg9gOwM7AE4FcDGwCGAjAG2gF4oBvKBCAdwAoA6RnVAcyQC4ocEQBtAXQCUnbiCgBfAFCSAZugTYAloiiKkMAjiRJachSJ6DykqFFQRg6VAii0TpqKEhwZUPZijEvUAOTvgygg+UABkIfamAPQAepia2gA6SJH0wBAotABi8kqI9GCocMBF4BCpcADKaIoILPSYOAQEujmCgvbtUrI5ASqYcBComBAA8lS0ACY4uAYgADRuCJzZCr02AD6wiCgY2PhERmT2iq60ahpaOjIIbcYOUP3IwA-baFjFqJ6LXEhbT7u4QgQCJmCxWGxUagvf7vOCoSbTHDtUziKAQAhIaBHe7mSzWRYI3DIiSSKRAA

Any suggestions on how to troubleshoot this problem?

Answer №1

Your custom type guard isClass requires a return type predicate: : func is Constructable

type Constructable = { new(...args: any[]): any }

function isClass(func: any): func is Constructable {
  return (
    typeof func === 'function' &&
    /^class\s/.test(Function.prototype.toString.call(func))
  )
}

function coerceOne(data: any, fn: Function | Constructable) {
  if (isClass(fn)) {
    const constructor = fn as Constructable
    return new constructor(data)
  } else {
    return fn(data)
  }
}

console.log(coerceOne('works', console.log))

Click here for more details

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

React JS displayed the string of /static/media/~ instead of rendering its markdown content

When I looked at the material UI blog template, I created my own blog app. I imported a markdown file using import post1 from './blog-posts/blog-post.1.md'; Next, I passed these properties to this component like so: <Markdown className=" ...

Effortlessly collapsing cards using Angular 2 and Bootstrap

Recently delving into Angular 2 and Bootstrap 4, I set up an about page using the card class from Bootstrap. Clicking on a card causes it to expand, and clicking again collapses it. Now, I want to enhance this by ensuring that only one card is open at a ti ...

Exploration of mapping in Angular using the HttpClient's post

After much consideration, I decided to update some outdated Angular Http code to use HttpClient. The app used to rely on Promise-based code, which has now been mostly removed. Here's a snippet of my old Promise function: public getUser(profileId: nu ...

Sending an event from a child component to another using parent component in Angular

My form consists of two parts: a fixed part with the Save Button and a modular part on top without a submit button. I have my own save button for performing multiple tasks before submitting the form, including emitting an Event to inform another component ...

What causes the oninput event to act differently in Angular as opposed to regular JavaScript?

As I delve into learning Angular with TypeScript, I've encountered some inconsistencies compared to JavaScript that are puzzling me. Take for example this function that works flawlessly with pure JavaScript, where it dynamically sets the min and max a ...

Is there a way to utilize req.query, req.params, or req.* beyond its original scope without the need to store it in a database?

Looking to streamline my code and apply the DRY pattern, I've been working on creating a helper function for my express http methods. The structure of each method is similar, but the req.params format varies between them. Here's how I attempted t ...

Ionic app: refresher functionality works in browser but not on iOS home screen app

I am currently developing a Progressive Web App (PWA) using Ionic, and I have implemented an ion-refresher in the app: <ion-content> <ion-refresher slot="fixed" (ionRefresh)="refresh()"> <ion-refresher-content pullingIcon="lines">& ...

Discovering an entry that lacks a specific value within an array in the records

Currently, I am utilizing sequelize along with typescript in a node environment (with a postgresql database). Here is the model that I have defined: id: number, someField: string, arr1: number[], arr2: number[] My objective is to retrieve all records wher ...

Can you use TypeScript to define generic React functional components?

I am looking to add annotations to a generic in a React functional component like the following: import React, {useEffect, useState} from "react"; interface PaginatedTableProps{ dataFetcher: (pageNumber: number) => Promise<any>, columnNames: ...

Error TS2322: Type 'boolean' cannot be assigned to type 'undefined'. What is the best approach for dynamically assigning optional properties?

I am currently working on defining an interface named ParsedArguments to assign properties to an object, and here is what it looks like: import {Rules} from "../Rules/types/Rules"; export interface ParsedArguments { //other props //... ...

How can I determine the existence of an S3 bucket and, if it doesn't exist, create it using TypeScript CDK?

I am currently facing an issue where I need to verify the existence of a bucket in the account and either create a new one if it doesn't exist or use the existing bucket My attempt at achieving this is as follows: import {Bucket} from 'aws-cdk-l ...

Custom fields provided by Express are not accessible within routes

In my customExpress.d.ts file, I have defined an extended type: declare namespace Express { export interface Request { user: { id: string; }; } } I have also configured it in the tsconfig.json file: ... "typeRoots": ["sr ...

TypeScript seems to be failing to detect the necessary checks before they are used

I've been pondering on how to ensure TypeScript acknowledges that I am verifying the existence of my variables before using them. Below is the code snippet : Here's the function responsible for these checks: function verifyEnvVars(){ if (!proc ...

Experimenting with a file system library function using Jest and Typescript alongside a placeholder function

When attempting to test a library function that uses the fs module, I received assistance in this question on Stack Overflow. The feedback suggested avoiding mocks for better testing, an approach I agreed with @unional. I am now facing a similar challenge ...

Ways to extend the default timeout duration in Angular

My server calls are taking a long time, around 30-40 minutes, and my Angular frontend is timing out. Is there a way to increase the default timeout for this service call? method1(id: number): Promise<number> { const body= JSON.stringify(id); ...

I can't figure out why I'm receiving undefined even though all the variables are populated with the necessary

I have been working on a project that involves implementing email and password authentication using Firebase. However, I encountered an error when the user submits their credentials: FirebaseError: Firebase: Error (auth/admin-restricted-operation). at ...

What's causing Angular to not display my CSS properly?

I am encountering an issue with the angular2-seed application. It seems unable to render my css when I place it in the index.html. index.html <!DOCTYPE html> <html lang="en"> <head> <base href="<%= APP_BASE %>"> < ...

Guide on invoking child components' functions from the parent component in Angular 6

Main Component import { Component } from '@angular/core'; import { DisplayComponent } from './display.component'; @Component({ selector: 'my-app', template: ` <button (click)="submit()">Call Child Com ...

The specified module '...' is identified as a non-module entity and therefore cannot be imported using this specific construct

Currently, I am facing an issue in my .tsx file where I am attempting to import a RaisedButton component from material-ui using the following code: import * as RaisedButton from 'material-ui/lib/raised-button' Unfortunately, this is triggering ...

Accessing and manipulating a intricate JSON structure within an Ionic 3 framework to seamlessly connect it to the user

I'm currently developing an app using Ionic 3. Within my project, I have a JSON object structured like this: { "player": { "username": "thelegend", "platform": "xbox", "stats": { "normal": { "shots ...