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

前端 未结 10 961
伪装坚强ぢ
伪装坚强ぢ 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:44

    You don't need to use never or add anything to the end of your switch.

    If

    • Your switch statement returns in each case
    • You have the strictNullChecks typescript compilation flag turned on
    • Your function has a specified return type
    • The return type is not undefined or void

    You will get an error if your switch statement is non-exhaustive as there will be a case where nothing is returned.

    From your example, if you do

    function getColorName(c: Color): string {
        switch(c) {
            case Color.Red:
                return 'red';
            case Color.Green:
                return 'green';
            // Forgot about Blue
        }
    }
    

    You will get the following compilation error:

    Function lacks ending return statement and return type does not include undefined.

提交回复
热议问题