How is it possible for the output to be a string array when the variable was declared as a number in TypeScript?

Snippet:

function sampleFunction(sample:string|number|string[])
{
    if(typeof sample == "string")
    {
        console.log("Sample is String " + sample);
    }
    else if(typeof sample == "number")
    {
        console.log("Sample is Number " + sample);
    }
    else{
        console.log("Sample is String Array " + sample);
    }
}
var sample:number; //Assigning the variable as a number
sampleFunction(sample); 

Console Output:

Sample is String Array undefined

Even though the var type is specified as "number", why does the output show "String array"?

Answer №1

The variable example has not been assigned a value, so by default it is considered as undefined, which explains why the final else statement in your code is being executed.

You can resolve this issue by setting the value of example before calling the function:

var example = 10;
test(example);
// Output will be: Number 10

Keep in mind that type declarations are utilized during compilation and do not impact the runtime behavior of your code.

Answer №2

While you've initialized a number variable, it's important to remember that without assigning a value to the variable, it will default to undefined in TypeScript. The properties you define for the variable will actually be properties of the value assigned to it, not the variable itself.

Answer №3

When working with TypeScript, we have the ability to assign a "type" to a variable from the beginning. However, it is important to remember that TypeScript files are ultimately converted into JavaScript for browser compatibility. If a variable is declared without a value in TypeScript, it defaults to undefined when executed.

For example, declaring var example:number; assigns a type to the variable but does not provide a value. As a result, the variable will be undefined at runtime, leading to the last else condition being triggered and printing:

Example is String Array undefined
.

Answer №4

Instead of passing an example variable that doesn't contain a value in the function, try passing a number. This might result in a string array type being displayed. The reason for this is that when it's undefined, the typeof undefined doesn't correspond to either a string or number, leading the code to execute the else block.

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

Incorporating Vue into a dated website by eliminating the div and replacing it with new dynamic Vue components

As I attempt to integrate Vue into my old website, I want the existing jQuery scripts to continue functioning and the old HTML content to be displayed. However, I am encountering an issue where the el element and its contents are being removed. This probl ...

Unable to call an object that may be 'undefined': Utilizing a function with a return object that includes asynchronous functions as properties

I have a function exported in my adapter.ts file: import type { Adapter } from "@lib/core/adapters"; export default function MyAdapter (): Adapter { return { async createUser (user: User) { ... }, async findUserByEmail (email ...

When using React with TypeScript, there seems to be an issue where using history.push to change the URL results in rendering the 404 page instead

I have gone through all the previous answers but none of them could solve my problem. I am new to React and currently working on a personal project where I use React with TypeScript, Redux, and Material UI. For some reason, when I try to redirect from ins ...

Is the API providing a response in the form of an HTML document

I just created a cutting-edge React application that leverages the power of "fetch" to fetch data from an API. Within my App component in the "App.js" file, you can find the following code snippet: function fetchData() { fetch(`WORKINGURLWITHAPIKEY`) ...

How can you make each <li> in an HTML list have a unique color?

Looking for a way to assign different colors to each <li> element in HTML? <ul> <li>Item 1</li> <li>Item 2</li> <li>Item 3</li> <ul> Here's how you want them displayed: Item 1 should be red Ite ...

Is it possible to test a Node CLI tool that is able to read from standard input with

I'm looking for a way to test and verify the different behaviors of stdin.isTTY in my Node CLI tool implementation. In my Node CLI tool, data can be passed either through the terminal or as command line arguments: cli.js #!/usr/bin/env node const ...

Error message in Typescript: When a class has initialized properties, a 'super' call must be the first statement in the constructor

I am currently facing some typescript errors in my project. Would you like to see a sample of the code that is causing the issue? Here is a snippet: module CoreWeb { export class Controller implements IController { public $q; ... This piece of cod ...

Creating a static Top Bar that remains unaffected by page refreshing using Ajax or any other method can be achieved by implementing JavaScript and CSS

I've designed a sleek top bar for my upcoming website project. Below is the CSS code snippet for creating this clean div bar: .topbar { display:block; width:100%; height:40px; background-color:#f5f5f5; } I'm looking to incorporate a simple .SWF ...

Use radio buttons to enable switching between different data options within a dropdown menu

I am working on a dropdown box that is populated dynamically using JSON data. The content in the dropdown can be categorized into 4 types, so I have included radio buttons to switch between these categories. I have created HTML code to toggle between manu ...

Steps for mandating the specification of a type parameter for a generic React component

When setting up a new instance of a generic React component, I noticed that the TypeScript type checker automatically defaults to unknown without requiring me to specify the type argument: Ideally, I would prefer if TypeScript prompted for the explicit ty ...

Issue with jQuery selector when handling AJAX response

I've been scratching my head trying to understand why this code isn't functioning as expected. To make things clearer, I created a simplified version of the issue on jsFiddle, where it works perfectly. Here's what I'm trying to achieve ...

Obtaining the value of a command argument with JavaScript in ASP.NET

<asp:LinkButton ID="lnkprogress" runat="server" class="label label-info" BackColor="#589FC2" CommandArgument='<%#Eval("BookingId")%>' OnClientClick="jk();" >In progress</asp:LinkButton> This LinkButton is present in a repeat ...

applying attributes to an element

Can you tell me why the addClass method is adding the class 'foo' to both the div and p element in the code snippet below? $('<div/>').after('<p></p>').addClass('foo') .filter('p').attr ...

Error: SQLite database file name must be specified

I'm currently working through this tutorial that guides us in building an app with next.js. The tutorial involves using sqlite and performing database testing. One of the key components of the tutorial is the 'database-test.js' file: cons ...

Angular 5 - Error: Uncaught ReferenceError: req variable is not defined

After upgrading my Angular project from version 4.4.3 to 5, I made sure to update all angular packages to the latest Angular 5.0.0 as per the guidelines provided. Additionally, I updated the angular CLI to version 1.5.0. However, ever since this update, I ...

Language translation API specifically designed to convert text content excluding any HTML formatting

I have a dilemma with translating text content in an HTML file into multiple languages based on user input. To accomplish this, I am utilizing the Microsoft Translator AJAX interface. The structure of my HTML file looks something like this; <h1>< ...

Utilizing trackingjs as an external library in Ionic2

I have been attempting to incorporate the trackingjs library (https://www.npmjs.com/package/tracking) into my ionic2 project. Following the guidelines in the documentation (https://ionicframework.com/docs/v2/resources/third-party-libs/), I was able to suc ...

Choosing custom element children once they're connected to the DOM: A guide

My goal is to retrieve the value of transaction-name__inputbox when the user clicks on the transaction-add__button. The function transactionAddHandler is triggered upon clicking the button. However, my attempt to select this element using document.querySe ...

Steps for showing personalized validation error messages in Angular 7

Is there a way to highlight the input field of a form with a red border and display the message Password is invalid when a user types in a password that does not match the set password? I have managed to see the red border indicating an error when I enter ...

Managing redundant asynchronous data in AngularJS

Imagine this scenario: In your AngularJS application, a user is spamming input which triggers numerous asynchronous data calls on the backend. This results in constant changes to the displayed data as each fetch request completes. Ideally, we want the fina ...