鉴于以下代码:

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> 不同,并且编译器不应该允许将一个分配给另一个。我在这里缺少什么?

最佳答案

在 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'.

关于typescript - 没有对 Typescript 中的泛型进行编译检查?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/60268301/

10-12 14:23
查看更多