Damkulul
Damkulul

Reputation: 1476

Why isn't the compiler throwing an error when assigining a number/bool to a string var

I am new to Typescript and I'm trying to understand how Javascript var types work, I created a simple class: and restricted the name property to string, but when I insert a number to my string variable I get no error and my string property holds the number as it was a string... am I missing something? When I debugged it, I found that name was 345. //done in ts

class Customer {
    public name: string = "";
    validate(input: string): string {
        alert("hey");
        return "hey";
    }
}

The code that uses my class

 <script>        
        var tito = new Customer();
        tito.name = 345;
    </script>

Upvotes: 1

Views: 42

Answers (1)

nbouchet
nbouchet

Reputation: 211

Assuming that the first portion of code was done using Typescript, the code that uses that class seems to be placed in an HTML and it's pure Javascript, that's why the types are not being checked, since this is not being compiled by Typescript. In order to use type checking your code needs to be placed in a .ts file:

// Inside a .ts file
var tito = new Customer();
tito.name = 345;

Upvotes: 4

Related Questions