Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript class: Why does this compile?

Tags:

I want to write a class like this:

class Foo {
    public someProp = '123';
}

but I mistyped and wrote this:

class Foo{
    public someProp: '123'; // not "="
}

I expect getting a compilation error but nothing happens. Why is it so?

like image 631
san1127 Avatar asked Jul 08 '17 16:07

san1127


1 Answers

Because TypeScript supports constatnts as type when you need to list allowed values in the field. It is not a bug. It is feature. :)

var x: '123';
var y: '123' | '456';

x = '123';
x = '456'; // Error
x = '789'; // Error

y = '123';
y = '456';
y = '789'; // Error

see TypeScript Playground

like image 101
Misaz Avatar answered Sep 23 '22 22:09

Misaz