如何解决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)
是IA
和IAll
的并集,为什么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);
前一段时间我有一个类似的问题,并且jcalz给出了惊人的详细答复(我仍然不完全理解...)。我鼓励您检查一下: https://stackoverflow.com/a/58632009/5554464
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。