【发布时间】:2018-07-20 17:12:51
【问题描述】:
我正在构建一个可插入的接口/类架构,以便“输出”可以插入“输入”。我很快发现,当我使用兼容的接口但使用不兼容的泛型时,TypeScript 不会引发任何警告或错误。有什么我做错了,我可以做更多的事情来强制正确检查,或者这根本不支持?打字稿 2.9.2
interface IValueA {
fooA(): void;
}
interface IValueB {
barB(): void;
}
interface ISomethingA<T> {
goToB(thing: ISomethingB<T>): void;
}
interface ISomethingB<T> {
goToA(thing: ISomethingA<T>): void;
}
interface ISomethingAS extends ISomethingA<string> {}
interface ISomethingAN extends ISomethingA<number> {}
interface ISomethingBS extends ISomethingB<string> {}
interface ISomethingBN extends ISomethingB<number> {}
export class SomethingA<T> implements ISomethingA<T> {
public goToB(thing: ISomethingB<T>): void {
console.log("SomethingA", "goToB", thing);
}
}
export class SomethingAN implements ISomethingAN {
public goToB(thing: ISomethingBN): void {
console.log("SomethingA", "goToB", thing);
}
}
export class SomethingAS implements ISomethingAS {
public goToB(thing: ISomethingBS): void {
console.log("SomethingA", "goToB", thing);
}
}
export class SomethingB<T> implements ISomethingB<T> {
public goToA(thing: ISomethingA<T>): void {
console.log("SomethingA", "goToA", thing);
}
}
export class SomethingBN implements ISomethingBN {
public goToA(thing: ISomethingAN): void {
console.log("SomethingA", "goToA", thing);
}
}
export class SomethingBS implements ISomethingBS {
public goToA(thing: ISomethingAS): void {
console.log("SomethingA", "goToA", thing);
}
}
const a = new SomethingA<IValueA>();
const b = new SomethingB<IValueB>();
const as = new SomethingAS();
const an = new SomethingAN();
const bs = new SomethingBS();
const bn = new SomethingBN();
a.goToB(b); // ISomethingA<IValueA> expects ISomethingB<IValueA> but accepts ISomethingB<IValueB>
as.goToB(bn); // ISomethingAS (ISomethingA<string>) expects ISomethingBS (ISomethingB<string>) but accepts ISomethingBN (ISomethingB<number>)
an.goToB(bs); // ISomethingAN (ISomethingA<number>) expects ISomethingBN (ISomethingB<number>) but accepts ISomethingBS (ISomethingB<string>)
【问题讨论】:
标签: typescript class generics types interface