What methods can TypeScript employ to comprehend this situation?

There's an interesting scenario when it comes to assigning a variable of type unknown to another variable. TypeScript requires us to perform type checking on the unknown variable, but how does TypeScript handle this specific situation? It appears that TypeScript is looking for a boolean response, but in reality, the solution may be more complex:

let first: unknown = 5;
let second: number;

const result = typeof first === 'number';

if(result){
    second = first; // error : Type 'unknown' is not assignable to type 'number'
}

if(typeof first === 'number'){
    second = first; // no errors
}

Answer №1

In June 2021, TypeScript introduced support for indirect expression type narrowing in version 4.4 after the addition of PR #44730. Anders Hejsberg, in the feature's introduction notes, highlighted the constraints of this new functionality (emphasis and formatting added):

Narrowing through indirect-references is applicable only when:

  • The conditional-expression or access to a discriminant-property is declared within a const variable without any type annotation, and...
  • The reference being narrowed down belongs to one of the following categories:
    • A const variable or
    • A readonly property or
    • A parameter with no assignments within the function body.

In situations where your assigned variable let first: unknown = 5; cannot utilize this new feature because it is defined as a let local variable instead of a const one.

If you switch the code to use const first instead of let first, then it will function correctly:


const first: unknown = 5;
let second: number;

const result = ( typeof first === 'number' );

if( result ) {
    second = first; // OK!
}

if( typeof first === 'number' ) {
    second = first; // OK!
}

Explore this concept on TypeScript Playground

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

Discover a method to deselect a checkbox within a separate component in angular15

I am currently dealing with Angular15 and I find myself stuck on an issue related to checkbox selection change. Situation: As per the requirements, I have a menu bar and a Checkbox. The Checkbox is generated from a reusable component which is used in the ...

"Upon invoking the services provider in Ionic 2, an unexpected undefined value was

I encountered an issue while setting a value in the constructor of my page's constructor class. I made a call to the provider to fetch data. Within the service call, I was able to retrieve the data successfully. However, when I tried to access my vari ...

The issue arises when Jest fails to align with a custom error type while utilizing dynamic imports

In my project, I have defined a custom error in a file named 'errors.ts': export class CustomError extends Error { constructor(message?: string) { super(message); Object.setPrototypeOf(this, Error.prototype); this.nam ...

Guide to specifying the indexer type of a function argument as T[K] being of type X in order for t[k]=x to be a permissible expression

Currently, I am attempting to create a function that can alter a boolean property within an object based on the provided object and property name. While I have found some helpful information here, the function body is still producing errors. Is there a way ...

Guide on successfully importing a pretrained model in Angular using TensorFlow.js

I need help with uploading a pretrained Keras model to my existing tensorflow.js model and then making simple predictions by passing tensors in the correct format. The model is stored locally within the project, in the assets folder. export class MotionAn ...

What is the best way to include a variable or literal as a value in styled components?

When it comes to managing various use cases, I always rely on props. However, I am currently facing a challenge in changing the border color of a styled input during its focus state. Is there a way to utilize props for this specific scenario? Despite my f ...

The Vue event was triggered, however there was no response

My current project consists of a Typescript + Vue application with one parent object and one component, which is the pager: //pager.ts @Component({ name: "pager", template: require("text!./pager.html") }) export default class Pager extends Vue { ...

To initiate the development environment, execute the following command: `cross-env NODE_ENV=

[email protected] start /Users/ssurisettii/Documents/il-17g5-app cross-env NODE_ENV=development npm run webpack-development sh: cross-env: command not found npm ERR! code ELIFECYCLE npm ERR! syscall spawn npm ERR! file sh npm ERR! errno ENOENT npm ER ...

Creating a Jsonifiable type that aligns with static interfaces: A step-by-step guide

When working with Typescript, there are 3 types that share similarities as they are composed of primitive types, maps, and arrays: type Color1 = { [component: string]: number } type Color2 = { green: number red: number blue: number } interface Colo ...

Enhance Express Middleware with Typescript for advanced functionality

Currently in the process of developing a REST API using Express and Typescript, I am encountering difficulties when trying to extend the Request/Response objects of Express. Although my IDE shows no errors, Typescript throws TS2339 Errors during compilati ...

Properties for a standard React component

Currently, I am developing a form component in react with typescript that requires a 'fieldStructures' and an 'onSubmit' prop. type FieldStructure { type: 'text'; name: string; label?: string; helpText?: string ...

Is there a way to access the badge hidden behind the collapsible menu in bootstrap 4?

After moving from bootstrap 3 to bootstrap 4, my items no longer align properly. I've scoured the entire Internet for a solution, but I've run out of options (and patience.. haha) This is how it currently looks: I want the badge to be positione ...

Is it possible for me to use an array as an argument for the rest parameter?

One of the functions in my codebase accepts a rest parameter. function getByIds(...ids: string){ ... } I have tested calling getByIds('andrew') and getByIds('andrew','jackson'), which successfully converts the strings into a ...

Creating a type or interface within a class in TypeScript allows for encapsulation of

I have a situation where I am trying to optimize my code by defining a derivative type inside a generic class in TypeScript. The goal is to avoid writing the derivative type every time, but I keep running into an error. Here is the current version that is ...

What is the best way to reset a dropdown list value in angular?

Is there a way to erase the selected value from an Angular dropdown list using either an x button or a clear button? Thank you. Code <div fxFlex fxLayout="row" formGroupName="people"> <mat-form-field appearance=&quo ...

Creating a factory function through typhography

I have a dynamically generated list of functions that take an argument and return different values: actions: [ param => ({name: param, value: 2}), param => ({label: param, quantity: 4}), ] Now I am looking to create a function that will gen ...

"Embracing the power of multiple inheritance with Types

I am struggling with the concept of multiple inheritance in TypeScript. It doesn't make sense to overload a hierarchy with too much functionality. I have a base class and several branches in the hierarchy. However, I need to utilize mixins to isolate ...

What is the method for displaying an object as JSON on the console in Angular2?

I've been utilizing a service to input my form data into an array within my angular2 application. The information is organized in the following manner: arr = [] arr.push({title:name}) After executing console.log(arr), it displays as Object. However, ...

Retrieving rows from a MySQL table that contain a specified BIGINT from an array parameter

I've encountered a problem with mysql while using serverless-mysql in TypeScript. It seems like my query might be incorrect. Here is how I am constructing the query: export default async function ExcuteQuery(query: any, values: any) { try { ...

Develop a PDF generator in ReactJS that allows users to specify the desired file name

Is there a way to customize the file name of a generated PDF using "@react-pdf/renderer": "^2.3.0"? Currently, when I download a PDF using the toolbar, it saves with a UID as the file name (e.g., "f983dad0-eb2c-480b-b3e9-574d71ab1 ...