Why does TypeScript accept value as a data type?

前端 未结 3 598
慢半拍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:38

    One reason would be to handle multiple types for the same variable. That's why typescript allows you to use specific values for types.

    let x: true | false | 'dog';
    x = true; // works
    x = false; // works
    x = 'cat'; // compilation error
    

    In this case let x: true is just a particular case where there is only one type.

    It looks like the string literal types functionality was exetended to allow for other types of values as well. Maybe there is a better documentation example for it but all I could find is the string literal types section in the handbook here.

提交回复
热议问题