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

What is the method for retrieving data from the root component within a child template in VueJs?

How can I access this.$root from within a VueJs template? For example: <template> <v-card elevation="this.$root.$refs.foo.cardElevation"> Foo </v-card> </template> I am aware that I can create a data property and ...

The navigation icon on my website refuses to close

Hey there, I'm having some trouble creating a side navigation menu. The issue I am facing is that the menu opens without any problem, but then I can't seem to figure out how to close it using a second "onclick()" function. If you could take a lo ...

Customizing a tinyMCE button with a unique icon

I'm attempting to insert a Font-Awsome icon into a button that I included in tinyMCE using the following code: ed.addButton('youtube', { title: 'Add Video' , icon: 'icon-youtube', onclick: function () { ...

Optimal method for identifying all inputs resembling text

I'm in the process of implementing keyboard shortcuts on a webpage, but I seem to be encountering a persistent bug. It is essential that keyboard shortcuts do not get activated while the user is typing in a text-like input field. The approach for hand ...

Guide to populating a full calendar using JSON information

Implementing the FUllCALENDAR CSS template for creating a meeting calendar has been my current project. The servlet class I am using is CalendarController. However, when running it, the output appears as follows: {"events":[{"id":1,"title":"1","s ...

What is the best way to fetch the title property from my Campaign Contract for displaying it in the render method?

I'm currently working on a unique crowdfunding DApp that requires constant access to contract variables through function calls for retrieval purposes. The getDeployedCampaigns function is responsible for returning an array of deployed campaign addres ...

Efficiently submitting multiple forms in a single click

On my photo portfolio admin page, I have created a feature to caption, keyword, and credit each photo. Previously, I had multiple forms listed dynamically with submit buttons for each form. With over 20 photos/forms on the page, this process became tedious ...

Issue with handling multiple input files in an *ngFor loop

I am facing difficulties in targeting the correct input within a *ngFor loop. When I include an image with the first input (Certificat dimmatriculation), it displays a placeholder image and a delete button to reset the input, but it appears under both divs ...

Ways to update the component's state externally

I'm new to Next.js (and React) and I'm attempting to update the state of a component from outside the component. Essentially, I am conditionally rendering HTML in the component and have a button inside the component that triggers a function to se ...

Is it planned to include StencilJS as a development choice in Ionic?

I'm curious about the potential adoption of Stencil JS for developing mobile apps within the Ionic framework. When I mention "an option for developing," I'm referring to frameworks like NativeScript where developers can choose between Angular + ...

The event listener $(window).on('popstate') does not function properly in Internet Explorer

$window 'popstate' event is not functioning properly in IE when using the browser back button. Here is the code snippet used to remove certain modal classes when navigating back. $(window).on('popstate', function(event) { event.pre ...

Issue encountered: Inability to implement asynchronous functionality within a forEach loop while making an API request

When making a GET API call, the code looks like this router.get('/review', async (req, res) => { try { const entity = await Entity.find(); const entityId = []; Object.keys(entity).forEach((key) => { entityId.push(entity[ ...

Numerous Kendo windows are layered on top of each other, yet the text divisions within them remain distinct

I am currently working on a project that involves laying out multiple Kendo windows in rows. Specifically, I need to display 4 windows in each row and have them shift left when closed. My framework of choice is Bootstrap 3. Everything works as expected w ...

What could be the reason for the react hook form failing to capture the data upon submission?

I am struggling to access the props' value after clicking the button, as it keeps returning undefined. My goal is to display the years of service and profession details based on the user's selection. return ( <form onSubmit={handleSubmit(o ...

Guide to Chrome's Document Object Model and JavaScript Reference

Does Chrome have a Javascript/DOM Reference page similar to the Mozilla Developer Network? I am curious about other websites that provide detailed information on Chrome's specific interpretations of web standards. ...

`Monitoring and adjusting page view during window resizing in a dynamic website`

Situation: Imagine we are reading content on a responsive page and decide to resize the browser window. As the window narrows, the content above extends down, making the entire page longer. This results in whatever content we were previously viewing bein ...

Export nested objects from an AngularJS JSON array to a CSV file

When I download my data into a CSV file, the display setting is showing as "[object Object]". This is not the desired outcome. https://i.stack.imgur.com/ej2UO.png The expected display should look like this: https://i.stack.imgur.com/8JJ88.png This is p ...

Using $route to obtain URL parameters

I am faced with the challenge of passing the last parameter from the following URL to a $http.get request in my Angular application. http://myurl.dev/users/32 However, I am struggling to figure out how to pass the 32 as the id. Here is what I have tried ...

Is it possible to use a single type predicate for multiple variables in order to achieve type inference?

Is there a way to optimize the repeated calls in this code snippet by applying a map to a type predicate so that TSC can still recognize A and B as iterables (which Sets are)? if(isSet(A) && isSet(B)) { ...

$q.all - successfully resolving some HTTP requests while encountering errors on others

I encountered a coding scenario like this angular.forEach(config.tvshows.shows, function(show) { promises.push($http.get('http://epguides.frecar.no/show/' + show.replace(/\s|\./g, '') + '/next/')); }); re ...