【问题标题】:Why does typescript show an error on this scenario with a union type?为什么 typescript 在这种情况下使用联合类型显示错误?
【发布时间】:2022-06-10 17:48:08
【问题描述】:

在这种情况下:

type Type = {
    a: string;
    b: string;
} | {
    a: number;
    b: number;
};

const func = ({a, b}: Type): string => {
    if (typeof a === 'string') {
        return b;
    }

    return 'w/e';
}

func({a: 1, b: 'w/e'});

return b; 声明出现错误

键入'字符串 | number' 不可分配给类型 'string'。

  类型“数字”不可分配给类型“字符串”。

根据我对错误的理解,Typescript 将 Type 类型解释为

type Type = {
    a: string | number;
    b: string | number;
};

,但即使是这样,为什么我不能用字符串和数字调用func函数呢?

调用状态错误

类型参数 '{ a: number; b:字符串; }' 不可分配给“Type”类型的参数。

  输入 '{ a: number; b:字符串; }' 不可分配给类型 '{ a: number; b:号码; }'。

    属性“b”的类型不兼容。

      类型“字符串”不能分配给类型“数字”。

(ts版本:4.7.2)

【问题讨论】:

  • 不,它不会像您想象的那样将其解释为联合。您有两个不同的选项,2 number 或 2 string - 但是您尝试使用 1 number 和 1 string 的组合来调用函数,而您的 Type 不允许这样做跨度>

标签: typescript


猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-07-22
  • 2018-04-10
  • 2023-03-16
  • 2014-03-24
  • 1970-01-01
  • 2022-11-27
  • 1970-01-01
相关资源
最近更新 更多