iamjc015
iamjc015

Reputation: 2237

Typescript doesn't type check on runtime

I am a beginner with typescript and playing with it on their Playground site. I have the following code:

class Queue<T> { 
    private data = [];

    push = (item: T) => this.data.push(item);
    pop = (): T => this.data.shift();
}



let button = document.createElement('button');
button.textContent = "Say Hello";
button.onclick = function () {
    let q = new Queue<number>();
    q.push("asdada");

    alert(q.pop(0));
}

document.body.appendChild(button);

As you can see I created a Queue Object to just accept a number. However, I was able to pass string and able to alert it on my browser. I saw the compiled JS version and it doesn't type check my variable. Isn't typescript supposed to avoid these errors? Or am I mistaken?

Thanks!

Upvotes: 5

Views: 5432

Answers (2)

agDev
agDev

Reputation: 865

Typescript will still output regular javascript, so if its valid javascript it will continue to work. it will only yell at you in the editor you're using.

If you prefer typescript should not generate javascript if there is an error use --noEmitOnError as Matt McCutchen suggested in the comments.

If you want to check the types at runtime you can use User-Defined Type Guards.

See this answer for a quick example.

Upvotes: 4

Matt McCutchen
Matt McCutchen

Reputation: 30879

Indeed, TypeScript does not check types at runtime. See the FAQ entry.

Upvotes: 6

Related Questions