Why does TypeScript accept value as a data type?

前端 未结 3 593
慢半拍i
慢半拍i 2020-12-16 18:22

Why does TypeScript accept value as a data type?

These scenarios below are accepting and non-acceptable declarations.

export class MyComponent{
           


        
3条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-16 18:42

    Why does TypeScript accept a value as a data type?

    This is extension of string literal types, this PR explains it: literal types

    How does JavaScript handle these at compile time?

    Its pure typescript creation, that will not affect resulting javascript.

    How does it differ from readonly and constant?

    Well - it will not be readonly. It will just allow one value. Check this example:

    export class MyComponent
    {
        readonly error = 1;
        error1: 1 = 1;
    
        public do()
        {
            this.error = 1; //Error. The field is readonly
            this.error1 = 1; //No error - because the field is not readonly
            this.error1 = 2; //Error. Type mismatch
        }
    }
    

提交回复
热议问题