Typescript class: Why is this compiling?

I want to write a class as follows:

class Foo { public someProp = '123'; } 

but I made a mistake and wrote this:

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

I expect to get a compilation error, but nothing will happen. Why is this so?

+5
source share
1 answer

Because TypeScript supports the constatnts type as a type, when you need to specify valid values ​​in a field. It's not a mistake. This is a 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

+4
source

Source: https://habr.com/ru/post/1269635/


All Articles