How do I check that a switch block is exhaustive in TypeScript?

前端 未结 10 944
伪装坚强ぢ
伪装坚强ぢ 2020-12-02 10:57

I have some code:

enum Color {
    Red,
    Green,
    Blue
}

function getColorName(c: Color): string {
    switch(c) {
        case Color.Red:
                     


        
10条回答
  •  执笔经年
    2020-12-02 11:22

    In really simple cases when you just need to return some string by enum value it's easier (IMHO) to use some constant to store dictionary of results instead of using switch. For example:

    enum Color {
        Red,
        Green,
        Blue
    }
    
    function getColorName(c: Color): string {
      const colorNames: Record = {
        [Color.Red]: `I'm red`,
        [Color.Green]: `I'm green`,
        [Color.Blue]: `I'm blue, dabudi dabudai`,   
      }
    
      return colorNames[c] || ''
    }
    

    So here you will have to mention every enum value in constant, otherwise you get an error like, for example, if Blue is missing:

    TS2741: Property 'Blue' is missing in type '{ [Color.Red]: string; [Color.Green]: string;' but required in type 'Record'.

    However it's often not the case and then it's really better to throw an error just like Ryan Cavanaugh proposed.

    Also I was a bit upset when found that this won't work also:

    function getColorName(c: Color): string {
        switch(c) {
            case Color.Red:
                return 'red';
            case Color.Green:
                return 'green';
        }
        return '' as never // I had some hope that it rises a type error, but it doesn't :)
    }
    

提交回复
热议问题