typescript中的测试联合返回

typescript中的测试联合返回,typescript,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) } 我得

我无法让简单的联合使用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)
}
我得到以下错误属性“error”在类型“{error:{code:number;message:string;}}}}{success:boolean;}”上不存在

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


谢谢

您可以像这样使用自定义类型的保护,尽管您可以根据自己的喜好使其简单或复杂。我已确保此示例作为独立示例运行:

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)
}

您可以尝试使用instaceof或只是检查属性是否存在并将其作为任何属性处理。谢谢,我认为这与可以动态推断联合类型的Flowtype相比有点冗长。但可能返回不同形状的值根本不是Typescript的方法: