What is the reason behind Typescript not needing me to explicitly narrow down this unknown variable

I have always associated 'unknown' with the concept of 'not sure,' and when I need to work with it, I believe the type should be narrowed down.

However, in this scenario, it does not behave as expected. Surprisingly, there is no error displayed by the following piece of code:

abstract class Foo<T> {

  abstract doth(input: T): void;

}

function checkAndDo(foo: Foo<unknown>) {

    const someRandomBS = 'afafaf';
    foo.doth(someRandomBS);

}

How can I define the type of checkAndDo's foo parameter to convey the idea: "I acknowledge it's a Foo, but I'm uncertain about the generic type parameter"?

Answer №1

The T parameter within the Foo function is considered to be in a contravariant position. If you are unsure about what inputs are accepted by the doth method, it is recommended to use never, indicating that you are unable to invoke the method. This is similar to utilizing unknown for types in covariant positions, where the type of an accessible value (such as an object property or function result) is unknown and cannot be utilized.

By using Foo<unknown>, you are essentially demanding a doth implementation that can handle any type of value (of an unknown type).

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

Enhancing function behavior with higher order functions for TypeScript method overriding

After examining this piece of code: /** * Transform a single-argument function into a function that can handle and return values wrapped in the type constructor `F` */ export function lift<F extends URIS3>( F: Functor3<F> ): <A, B>(f ...

How can I show a limited number of columns in a mat-table in Angular 6 depending on a specific condition?

Currently, I am facing an issue with my mat table as it contains several columns. In a specific scenario, I need to hide two of these columns. Typically, for a regular table, we would use a simple ngIf condition to achieve this. However, in the case of thi ...

Issue with routing during startup of Ionic 4 application

We are currently working on a project using Ionic 4 along with Angular framework. One of the issues we are facing is related to logging into the application. Below is a screenshot illustrating the error: Here is the snippet of my code: import { NgModul ...

The 'substr' property is not found in the type 'string | string[]'

Recently, I had a JavaScript code that was working fine. Now, I'm in the process of converting it to TypeScript. var ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress; if (ip.substr(0, 7) == "::ffff ...

Exploring the concept of object inheritance in Angular 5 with Typescript

I'm facing a challenge related to inheritance while building my initial angular 5 application. The error message I encounter is: Property 'message' does not exist on type 'CouponEvent', as reported by the angular-cli. export class ...

Error: Failed to locate package "package-name" in the "npm" registry during yarn installation

While working on a large project with numerous sub-projects, I attempted to install two new packages. However, YARN was unable to locate the packages despite the .npmrc being present in the main directory. ...

Troubleshooting Angular2 Error: Incompatibility with TypeScript - Unable to Assign String

While working on creating a custom pipe in Angular2 for filtering, I encountered the following build error: Error TS2322: Build: Type '() => string' is not assignable to type 'string' Below is my sample code: import { PipeTransf ...

Encountering an issue with a MEAN application using Angular 2: The error message states "Cannot read property

As a first-time application developer, I am working on creating a system to manage Client profiles. Utilizing the Angular tour of heroes for the basic structure, I integrated mongodb and express components sourced from various online platforms. However, I ...

javascript and TypeScript errors in React

Currently in the process of learning how to implement typescript with react. I initially found react-scripts-ts to be slow, which discouraged me. I have now tried out the new typescript setup with babel 7 (react-webpack-typescript-babel) and it is impressi ...

Extracting live TV channels from an m3u file by differentiating them from VOD content

Currently, I am developing an IPTV player app and have successfully parsed the m3u file. My current challenge is separating live TV channels from Video on Demand (VOD). I am unsure of where exactly the transition happens in the playlists. Below are the ke ...

The module 'DynamicTestModule' has imported an unexpected directive called 'InformationComponent'. To resolve this issue, please include a @NgModule annotation

Even though I found a similar solution on Stackoverflow, it didn't resolve my issue. So, let me explain my scenario. When running the ng test command, I encountered the following error: Failed: Unexpected directive 'InformationComponent' i ...

I am trying to replace the buttons with a dropdown menu for changing graphs, but unfortunately my function does not seem to work with the <select> element. It works perfectly fine with buttons though

I am currently working on my html and ts code, aiming to implement a dropdown feature for switching between different graphs via the chartType function. The issue I am facing is that an error keeps popping up stating that chartType is not recognized as a ...

Creating a RESTful API with Express, Firestore, Cloud Functions, and TypeScript

In my quest to create a REST API for my app, I've been delving into tutorials on Firestore & Cloud Functions. Unfortunately, all the ones I've come across are either outdated or simply don't work. This has been quite frustrating for me a ...

What steps should I take to fix this TypeScript error?

I've been struggling to fix this error, but I'm unsure of the best way to resolve it. Here is the code snippet I've been working with:https://i.sstatic.net/m6M48.png Here is the specific error message: https://i.sstatic.net/uk6QY.png ...

JavaScript Error: Cannot read property 'b' of undefined

Whenever I attempt to establish inheritance in TypeScript, the following JavaScript code is generated: var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constr ...

In Angular-Cli, the variables @Input and @Output are consistently null until they are assigned

Individuals' internal values are printed without any problems, but those obtained using @Input or @Output are not being displayed. child.component.ts @Component({ selector: 'app-form-input', templateUrl: './form-input.component.ht ...

Retrieve the row from the table using the "let" keyword

I'm attempting to retrieve the row of a table by selecting a radio button. My goal is to identify the selected row in order to access the experiment ID, but when I try this, the alert shows "Row index is: undefined." I found the code at: https://www. ...

Angular 4 - Issue with data retention beyond subscription boundaries

Within my Angular service, I have the following code: this.signInService.signIn(this.model).subscribe(user => { this.user = user, console.log(this.user.Username) }); console.log(this.user.Username); There are two instances of console.log st ...

What is the proper way to address the error message regarding requestAnimationFrame exceeding the permitted time limit?

My Angular application is quite complex and relies heavily on pure cesium. Upon startup, I am encountering numerous warnings such as: Violation ‘requestAnimationFrame’ handler took 742ms. Violation ‘load’ handler took 80ms. I attempted to resolve ...

Calculate the total number of seconds from an ISO8601 duration with TypeScript by utilizing the date-fns library

Given an ISO8601 duration string like "PT1M14S," I am looking to convert it to seconds as an Integer using the date-fns library in TypeScript. ...