相关疑难解决方法(0)

如何让 Discriminated Unions 与解构一起工作?

考虑以下三种类型中,MainType是工会Type1Type2。如果kind"kind1"那么data应该是{msg: string}相同的类型Type2

interface Type1 {
    kind: "kind1";
    data: { msg: string };
}
interface Type2 {
    kind: "kind2";
    data: { msg2: string };
}

type MainType = Type1 | Type2;
Run Code Online (Sandbox Code Playgroud)

这是使用它的第一种方法。

function func(obj: MainType) {
    switch (obj.kind) {
        case "kind1": return obj.data.msg;
        case "kind2": return obj.data.msg2;
    }
}
Run Code Online (Sandbox Code Playgroud)

上面的代码没有给出错误并显示正确的自动完成。

但是当我们解构obj它时,它会出错。

function func({kind, data}: MainType) {
    switch (kind) {
        case "kind1": return data.msg;
        case …
Run Code Online (Sandbox Code Playgroud)

javascript typescript

4
推荐指数
1
解决办法
641
查看次数

标签 统计

javascript ×1

typescript ×1