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

Typescript-联合类型和泛型类型引发不兼容错误,typescript,typescript-generics,union-types,Typescript,Typescript Generics,Union Types,我对泛型类型处理联合类型有问题。在我的例子中,一个函数是使用联合类型定义的,当我用联合类型中的一个元素调用这个函数时,我得到了一个错误,我一整天都在试图解释这个错误 我设法总结了以下几行代码: interface IA { a: string; } interface IB { b: string; } type IAll = IA | IB; interface IG<T> { prop: T; fct: (p: T) => void; } functio

我对泛型类型处理联合类型有问题。在我的例子中,一个函数是使用联合类型定义的,当我用联合类型中的一个元素调用这个函数时,我得到了一个错误,我一整天都在试图解释这个错误

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

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);
为什么
IA
的元素不能应用于
IAll
类型,而
IAll
IA
IB
的联合体?根据我的理解,如果
IA
匹配,检查
IB
是不相关的

fAll(a为IG)修复了这个问题,但我不明白为什么有必要这么做

谢谢你的帮助

问题在于
IG | IG
IG
不同。如果您将代码更改为第一个,它将工作,但是您将无法调用这样的函数

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);
接口IA{
a:弦;
}
接口IB{
b:弦;
}
IAll型=IA | IB型;
接口IG{
道具:T;
fct:(p:T)=>无效;
}
功能下降(p:IG){
//p.fct将允许'IA | IB'作为参数。这不是您想要的。
p、 fct({
b:“字符串”
})
返回;
}
常数a:IG={
道具:{a:“aaa”},
fct:(p)=>{
//这将注销'p.a',但'p.a'不必由'fAll'函数提供(见上文)。
控制台日志(每年);
}
};
秋季(a);
功能失效固定(p:IG | IG){
//那更好!
p、 fct({
b:“字符串”
})
返回;
}
(一);

不久前,我有一个类似的问题,从jcalz那里得到了一个非常详细的答复(我仍然不完全理解…)。我鼓励您检查一下:

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