What is the reason TypeScript does not display an error when assigning a primitive string to an object String?

From my understanding in TypeScript, string is considered as a primitive type while String is an object. Let's take a look at the code snippet below:

let s: string = new String("foo"); // ERROR 
let S: String = "foo"; // OK

It's interesting to note that we do not get an error on the second line even though we are technically using a string object rather than a string primitive. This behavior raises the question of why there is no error in this scenario.

Answer №1

The initial line will throw an error because attempting to assign a boxed type to a primitive type, which is more specific.

The following line will not generate an error since converting a primitive type to a boxed type, which is less specific.

Returning to the first line:

let str = new String("bar");
console.log(typeof str); // object

The error message is really accurate:

'string' is classified as a primitive, while 'String' is considered a wrapper object.

You can still make it work by using type assertion: TypeScript complies, and then JavaScript unboxes the variable. Nevertheless, I struggle to comprehend why one may want to do such a thing:

let strVar: string = new String("bar") as string; // OK

Interestingly, you are also able to perform conversions with a slightly similar syntax:

let stringValue: string = String("baz"); // OK
console.log(typeof stringValue); // string

This approach proves to be particularly handy for Boolean conversions, like in this example:

const itemAvailable = Boolean(itemInStock);
console.log(typeof itemAvailable); // boolean

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

Retrieving data using a class in an AJAX form submission

I am attempting to use AJAX to submit an HTML form. Here is my HTML: <form class="lyrics"> <input type="text" value="" id="song" name="song"> <button type="submit" class="btn btn-info lirik">lyrics</button> </form> ...

Using inertia-links within the storybook framework

Hey there, just wanted to share my experience with storybook - I'm really enjoying it so far! Currently, I'm facing a challenge while implementing it in my Laravel app with Inertia. I'm trying to render a navigation link component that make ...

Link Quick Techniques

I currently have an Express server set up with CRUD methods My goal is to automatically trigger the get method whenever a post, put, or delete request is made. This will ensure that the view on the Front-end side gets updated accordingly. Below is an exc ...

Having trouble retrieving alert message after submitting form using jquery

Trying to submit a form using jQuery, but when clicking on the submit button it displays a blank page. I understand that a blank page typically means the form has been submitted, but I want to show an alert() for testing purposes instead. However, it only ...

Send an object from AngularJS to an MVC controller and bind it to a corresponding class object

Trying to map an object from AngularJS to a custom C# class in an MVC controller, but encountering issues with the class object showing up as null. Here's the code snippet: $scope.Get = function () { var EService = [{ id: $scope.Id, ...

The error message "Property 'map' is not found on type 'User' in React with typescript"

I am currently experimenting with React using TypeScript. I have set up useState with an object but I am encountering issues trying to use the map function with that object. Below is the error message I am facing: Property 'map' does not exist ...

Manipulating datetime format within an input element of type date using Angular's ngModel

I have a date input in my form that is populated from the controller with a string value for 'dateOfDiagnosis'. The format of this string includes the time as well, like this: "2010-09-08T00:00:00" To bind this value to an input field in Angu ...

"What could be causing my React Native app to build without any issues even though the TypeScript compiler is throwing

Recently, I decided to explore TypeScript in combination with Expo. I took the time to set up linter and formatter integrations like typescript-eslint to help me catch errors while coding. Periodically, I run npx tsc to ensure my code compiles correctly an ...

The jQuery click event does not fire within a bootstrap carousel

I am trying to set up a bootstrap carousel where clicking on an image inside it will trigger a self-made lightbox. However, I am facing some issues with the JavaScript code not being triggered with the following syntax: $('html').on("click", ".l ...

What could be the reason behind the improper display of JavaScript for ID overlay2?

Why is it that when I try to have two overlays with different messages display upon clicking buttons, they both end up showing the same message? Even after changing the ID tag names, the issue persists. Can someone shed some light on what might be causin ...

Tips for inserting a property into an array of objects when it matches the specified ID

As someone new to Angular, I am encountering an issue and would appreciate some help. Here is an array of objects I am working with: signals = [{ 'signalID': '123' },{ 'signalID': '233' },{ 'signalID': &apo ...

Tricks to access value from a Nativescript array of Switch elements when tapping a Button

Scenario: In my project, I am using Nativescript 5.0 with Angular. The data is fetched from an API and displayed in customers.component.ts I am successfully rendering the elements based on the received IDs in customers.component.html When the user inter ...

Ways to obtain the output of an If/Else statement

It seems like I might be missing something, but I am unsure of how to extract the result from an else-if statement. Take this code snippet that I've been working on for example: In this scenario, the output would read "It's warm!", and what I wa ...

Use CSS media queries to swap out the map for an embedded image

Looking to make a change on my index page - swapping out a long Google Map for an embedded image version on mobile. The map displays fine on desktop, but on mobile it's too lengthy and makes scrolling difficult. I already adjusted the JS setting to "s ...

The creation of a Firebase user account with the specified email and password

I'm currently facing an issue while creating a new user with email and password using firebase authentication. The problem arises when I try to access the displayName from the returned async call before the updateProfile function, as it returns a null ...

Updating state with new data in React: A step-by-step guide

Recently, I delved into the world of reactjs and embarked on a journey to fetch data from an API: constructor(){ super(); this.state = {data: false} this.nextProps ={}; axios.get('https://jsonplaceholder.typicode.com/posts') ...

My worker threads seem to be flying under the radar

Currently, I am working on implementing worker threads into my Node.js/Typescript application. I have made significant progress, but it appears that my worker threads are not being executed as expected. Despite adding loggers inside the function intended f ...

Retrieve the currently displayed page on a bootstrap table

I'm currently utilizing the bootstrap table to showcase my data. One of the features I have added is a column with an edit button for each row. Upon clicking on the edit button, I open a bootstrap modal that displays the data from the corresponding ro ...

Click on the button to retrieve the data from the table cell

I have a table created using JavaScript <table class="table"> <thead> <tr> <th scope="col">#</th> <th scope="col">City</th> <th scope="col">Region</th> </tr> < ...

Incomplete Loading of Google Maps

Let me clarify that the solutions I have come across so far have not been successful. I am attempting to display a modal alert with a basic Google Maps integration. Problem: Google Maps does not load completely. Snippet from my .js file: var map; functi ...