The TypeScript error "Issue with Type Assertion: 'This expression is not callable Type'...' has no call signatures" occurs when there is a missing semicolon

Here's a simplified version of our original code:

  const start: number = 10
  const end: number = 20
  (someElement as HTMLInputElement).setSelectionRange(start, end)

We encountered an error with the 20, where a red squiggly line appeared indicating: This expression is not callable Type 'Number' has no call signatures. The solution we found was to add a semicolon:

  const start: number = 10
  const end: number = 20;
  (someElement as HTMLInputElement).setSelectionRange(start, end)

Any thoughts on why it compiled in that way? It seems like typescript being transformed into javascript interpreted the code differently and tried to treat the end variable as a function.

  const start: number = 10
  const end: number = 20(someElement as HTMLInputElement).setSelectionRange(start, end)

Answer №1

This issue is not specific to TypeScript; it occurs in plain JavaScript as well. The TypeScript compiler does not convert correct TypeScript into incorrect JavaScript intentionally. Instead, it transpiles unusual TypeScript code into the equivalent unusual JavaScript code.

In most cases, automatic semicolon insertion does not occur if the next token after a line terminator is possibly syntactically valid, except in specific situations where line terminators are not allowed. The open parenthesis "(" following "20" can be interpreted as the beginning of a function call, which is considered syntactically valid. Therefore, no semicolon is automatically inserted because a line terminator is permitted after "20."

Error Type: calling literal 20 which has no call signature for runtime check - and that is a good thing!

If you were using plain JavaScript instead of TypeScript (without type assertions), the JavaScript runtime would interpret the code similarly and throw a runtime error rather than a compile-time warning:

// This is plain JS, not TS 
try {
  const someElement = document.getElementsByTagName("input").item(0);
  const start = 10
  const end = 20
  (someElement).setSelectionRange(start, end)
} catch (e) {
  console.log("OOPS I CAUGHT AN ERROR");
  console.log(e.message); // 20 is not a function
}

Running this snippet without a TypeScript compiler will result in a TypeError from your browser's JavaScript runtime, indicating that "20" is not a valid function.

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

Adding attributes to parent DOM elements of a component in Angular2: A Step-by-Step Guide

I'm working with the following code: ... <div class="container"> <div class="fancy"> <fancybutton></fancybutton> </div> <button (click)="addAttribute()">Remove</button> <button (click)="remAttr ...

RC7 is missing the necessary HTTP_PROVIDERS for the resolveAndCreate HTTP method in Angular2

During the time of RC4, I was able to create my own custom http instance using a function like this: export function createHTTP(url:string, headers?:Headers){ let injector = ReflectiveInjector.resolveAndCreate([ myHttp, {provide:'defaultUrl ...

Importing BrowserAnimationsModule in the core module may lead to dysfunctional behavior

When restructuring a larger app, I divided it into modules such as feature modules, core module, and shared module. Utilizing Angular Material required me to import BrowserAnimationsModule, which I initially placed in the Shared Module. Everything function ...

"Ionic Calendar 2 - The ultimate tool for organizing your

I am using a calendar in my Ionic app that retrieves events from a database through an API. var xhr = new XMLHttpRequest(); xhr.open('GET', 'http://portalemme2.com.br/SaoJoseAPI/agenda', true); this.http.get('http://portalemme2.c ...

What is the best way to asynchronously refresh Angular 2 (or 4) PrimeNg Charts?

Issue: How can PrimeNg Charts be updated asynchronously? Situation: I have a dropdown menu that should trigger a chart refresh based on the user's selection. I believed I had the solution figured out, understanding Angular change detection and reali ...

What is the best way to upload a file using a relative path in Playwright with TypeScript?

Trying to figure out how to upload a file in a TypeScript test using Playwright. const fileWithPath = './abc.jpg'; const [fileChooser] = await Promise.all([ page.waitForEvent('filechooser'), page.getByRole('button' ...

The ngAfterContentInit lifecycle hook is not triggered when the parent component updates the child component

I am trying to understand the functionality of the ngOnChanges callback in Angular. I have implemented it to observe changes in a property annotated with the Input decorator as shown below: @Input() postsToAddToList: Post[] = []; However, after compiling ...

Divide the enhanced document into sections using TypeScript

In my project, I am working with Material UI and TypeScript. I have noticed that I need to declare the Theme interface and ThemeOptions in the same file for it to work properly. Is there a more efficient way to separate these declarations from the main t ...

How to efficiently display nested object data using Angular Keyvalue pipe

I am facing an issue with a particular HTTP request that returns an observable object containing multiple properties. One of these properties is the 'weight' object which has two key values, imperial and metric. While attempting to loop through ...

An automatic conversion cannot handle spaces and prohibited characters in Object keys

The AlphaVantage API uses spaces and periods in the keys. Their API documentation is not formal, but you can find it in their demo URL. In my Typescript application, I have created data structures for this purpose (feel free to use them once we solve the ...

"Every time you run mat sort, it works flawlessly once before encountering an

I am having an issue with a dynamic mat table that includes sorting functionality. dataSource: MatTableDataSource<MemberList>; @Output() walkthroughData: EventEmitter<number> = new EventEmitter(); @ViewChild(MatSort, { static: true }) sort ...

There is no 'next' property available

export function handleFiles(){ let files = retrieveFiles(); files.next(); } export function* retrieveFiles(){ for(var i=0;i<10;i++){ yield i; } } while experimenting with generators in T ...

Tips on sorting a FileList object selected by a directory picker in JavaScript/TypeScript

I need to filter or eliminate certain files from a FileList object that I obtained from a directory chooser. <input type="file" accept="image/*" webkitdirectory directory multiple> Within my .ts file: public fileChangeListener($event: any) { let ...

Angular: Elf facade base class implementation for utilizing store mechanics

What is the most effective way to access the store within a facade base class, allowing for the encapsulation of commonly used methods for interacting with the store? Imagine we have a store (repository) export class SomeRepository { private readonly s ...

Achieving VS Code/typescript autocomplete functionality without the need to import the library

When a module (for example, moment.js, knockout, or big.js) is added with a <script> tag like this: <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.js"> </script> that defines a global property (for instance ...

Running into issues with TypeScript in conjunction with Redux-Form and React-Redux connect

My excitement for TypeScript grew until I encountered some frustrating incompatibilities between Redux-Form and React-Redux. I am aiming to wrap a component decorated with reduxForm using the connect decorator from react-redux—this method has always bee ...

Exploring the potential of the forkJoin operator in Angular 4's Observable

I'm currently facing a challenge that involves retrieving both administrators and professionals from the "users" collection using AngularFire's latest version. I am utilizing Observables for this task. My goal is to make two parallel requests an ...

Transforming Uint8Array into BigInt using Javascript

I've come across 3 different ways to convert a Uint8Array to BigInt, but each method seems to produce varying results. Can someone clarify which approach is correct and recommended? Utilizing the bigint-conversion library. The function bigintConversi ...

When the value is empty, MUI Autocomplete will highlight all items

I have encountered a specific issue. I am working on developing a custom Autocomplete Component for filtering purposes. However, I recently came across the following Warning. MUI: The value provided to Autocomplete is invalid. None of the options matc ...

Why am I unable to retrieve the property from the JSON file?

Below is the provided JSON data: data = { "company_name": "חברה לדוגמה", "audit_period_begin": "01/01/2021", "audit_period_end": "31/12/2021", "reports": [ ...