Typescript-联合类型和泛型类型引发不兼容错误

问题描述

我对使用联合类型的泛型类型有疑问。就我而言,一个函数是使用联合类型定义的,当我用联合中类型之一的元素调用函数时,我会整天试图解释一个错误

我设法总结了以下几行代码

</div>

最后一行interface IA { a: string; } interface IB { b: string; } type IAll = IA | IB; interface IG<T> { prop: T; fct: (p: T) => void; } function fAll(p: IG<IAll>) { return; } const a: IG<IA> = { prop: {a: "aaa"},fct: (p) => { return; } }; fAll(a); 返回一个我无法解释的输入错误

fAll(a);

为什么Argument of type 'IG<IA>' is not assignable to parameter of type 'IG<IAll>'. Types of property 'fct' are incompatible. Type '(p: IA) => void' is not assignable to type '(p: IAll) => void'. Types of parameters 'p' and 'p' are incompatible. Type 'IAll' is not assignable to type 'IA'. Type 'IB' is not assignable to type 'IA'.ts(2345) IAIAll的并集,为什么IAll的元素不能应用为IA类型?据我了解,如果IB匹配,则检查IA是不相关的。

写作IB解决了这个问题,但我不明白为什么应该这样做。

感谢您的帮助!

解决方法

问题在于IG<IA> | IG<IB>IG<IA | IB>不同。如果将代码更改为第一个代码,它将可以使用,但是您将无法调用类似的函数。

interface IA {
  a: string;
}
interface IB {
  b: string;
}
type IAll = IA | IB;

interface IG<T> {
  prop: T;
  fct: (p: T) => void;
}

function fAll(p: IG<IAll>) {
  // p.fct will allow `IA | IB` as parameters. This is not what you're looking for.
  p.fct({
    b: "string"
  })
  return;
}

const a: IG<IA> = {
  prop: {a: "aaa"},fct: (p) => {
    // This will log out `p.a`,but `p.a` doesn't have to be provided by `fAll` function (see above).
    console.log(p.a);
  }
};

fAll(a);

function fAllFixed(p: IG<IA> | IG<IB>) {
  // Thats better!
  p.fct({
    b: "string"
  })
  return;
}

fAllFixed(a);

Playground

前一段时间我有一个类似的问题,并且jcalz给出了惊人的详细答复(我仍然不完全理解...)。我鼓励您检查一下: https://stackoverflow.com/a/58632009/5554464