给出以下代码:
interface Contract<T> {
}
class Deal<D> implements Contract<D> {
}
class Agreement<A> implements Contract<A> {
}
我希望它不会编译:
let deal:Contract<number> = new Deal<number>()
let agreement:Contract<string> = new Agreement<string>()
// expects this to not compile
agreement = deal;
或这个
let deal:Deal<number> = new Deal<number>()
let agreement:Agreement<string> = new Agreement<string>()
// expects this to not compile
agreement = deal;
但是它们都可以编译!
这里是游乐场link
我希望GenericOf<A>
与Genericof<B>
不同,并且编译器不应允许将一个分配给另一个。我在这里想念什么?
答案 0 :(得分:4)
在TypeScript中,类型参数仅在作为成员类型的一部分使用时才影响结果类型。有关更多详细信息,请参见the relevant documentation。
如果您实际上使用泛型,则确实会得到预期的错误:
interface Contract<T> {
log: (value: T) => void
}
class Deal<D> implements Contract<D> {
log(value: D) {
console.log(value)
}
}
class Agreement<A> implements Contract<A> {
log(value: A) {
console.log(value)
}
}
let deal: Contract<number> = new Deal<number>()
let agreement: Contract<string> = new Agreement<string>()
agreement = deal;
// Error: Type 'Contract<number>' is not assignable to type 'Contract<string>'. Type 'string' is not assignable to type 'number'.