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

前端 未结 10 957
伪装坚强ぢ
伪装坚强ぢ 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条回答
  •  Happy的楠姐
    2020-12-02 11:41

    To avoid Typescript or linter warnings:

        default:
            ((_: never): void => {})(c);
    

    in context:

    function getColorName(c: Color): string {
        switch(c) {
            case Color.Red:
                return 'red';
            case Color.Green:
                return 'green';
            default:
                ((_: never): void => {})(c);
        }
    }
    

    The difference between this solution and the others is

    • there are no unreferenced named variables
    • it does not throw an exception since Typescript will enforce that the code will never execute anyway

提交回复
热议问题