测试联合返回打字稿

时间:2017-03-06 15:49:12

标签: typescript

我无法使用typescript

来使用简单的联合

考虑以下代码

function test(v: boolean) {
    if (v === true) {
        return { success: 'yolo' }
    }
    return { error: { code: 32, message: 'nop' } }
}

const val = test(true)

if (val.error) {
    alert(val.error.message)
}

我收到以下错误Property 'error' does not exist on type '{ error: { code: number; message: string; } } | { success: boolean; }'

有没有办法测试返回union中的哪个值?

谢谢!

1 个答案:

答案 0 :(得分:1)

您可以使用自定义类型防护,就像这样 - 尽管您可以根据需要使其变得简单或复杂。我已经确定这个例子是一个独立的例子:

interface SuccessExample {
    success: string;
}

interface ErrorExample {
    error: { code: number; message: string }
}

function test(v: boolean) : SuccessExample | ErrorExample {
    if (v === true) {
        return { success: 'yolo' }
    }
    return { error: { code: 32, message: 'nop' } }
}

// Custom Type Guard - you can be as simple or complex as you like
function isError(arg: any): arg is ErrorExample {
    return arg.error !== undefined
        && arg.error.code !== undefined
        && arg.error.success !== undefined;
}

const val = test(true)

if (isError(val)) {
    alert(val.error.message)
}
相关问题