条件联合类型开关打字中的打字稿类型安全性

时间:2019-04-16 14:10:59

标签: typescript switch-statement union-types

我有一个简单的函数,将联合类型和boolean作为参数,并且无法通过Typescript进行键入。

我有此代码(playground here):

type A = 'a' | 'A';

function f(a: A, b: boolean): string {
    if (b) {
        switch (a) {
            case 'a': return '';
            case 'A': return '';
        }
    } else {
        switch (a) {
            case 'a': return '';
            case 'A': return '';
        }
    }
}

编译器(启用strictNullChecks时告诉我Function lacks ending return statement and return type does not include 'undefined'.

我真的不想添加default案例,因为这里的目的是确保在A中添加新类型时,可以在f中正确处理它们。而且我看不到我缺少哪个分支。

我可以通过写来解决(请参见链接的游乐场):

function g(a: A): string {
    switch (a) {
        case 'a': return '';
        case 'A': return '';
    }
}

function f2(a: A, b: boolean): string {
    if (b) {
        return g(a);
    } else {
        return g(a);
    }
}

(当然,在现实生活中,我需要两个不同的g函数,但是对于打字问题,这并不重要)。

如何在不引入f之类的中间函数的情况下让打字稿编译g

1 个答案:

答案 0 :(得分:1)

您可以添加default大小写进行修复,例如

function f(a: A, b: boolean): string {
    if (b) {
        switch (a) {
            case 'a': return '';
            case 'A':
            default: return '';
        }
    } else {
        switch (a) {
            case 'a': return '';
            case 'A':
            default: return '';
        }
    }
}

您还可以通过返回never类型来修复它,例如

function f(a: A, b: boolean): string {
    if (b) {
        switch (a) {
            case 'a': return '';
            case 'A': return '';
            default:
                const _exhaustiveCheck: never = a;
                return _exhaustiveCheck;
        }
    } else {
        switch (a) {
            case 'a': return '';
            case 'A': return '';
            default:
                const _exhaustiveCheck: never = a;
                return _exhaustiveCheck;
        }
    }
}
相关问题