TypeScript 在违反坚实原则时不会抛出错误

问题描述 投票:0回答:1

在 Java 中,当我们尝试执行以下情况(多态性)时,它会给我们一个编译错误/异常,这是预期的。但在打字稿中它不会给我们错误。为什么?.

虽然我们没有扩展类,或者更确切地说,接口,并且我们在发送对象数组的循环中调用按以下方式实现的方法,但它通常会给出编译错误(在 Java 中)。但在打字稿中,为什么它不仅允许编译,而且即使对象不属于类/接口,它也会运行执行方法。 当我们对所有接口事物应用 SOLID 原则时,按类/接口进行过滤的过程非常有用。 为什么打字稿会发生这种情况?这违反了原则。

class Developer {
    drink() {
        console.log(" drink coffee ");
    }
}
class Musician {
    drink() {
        console.log(" drink beer ");
    }
}
class Vintage extends Developer {
    drink() {
        console.log(" drink tea ");
    }
}

class Vegan {
    drink() {
        console.log(" drink water, ??????"); 
    }
}
function queue(processes: Array<Developer & Musician>) {
    processes.forEach(p=>p.drink());
}

let p = [
    new Developer(),
    new Musician(),
    new Vintage(),
    new Vegan(), // Why is this happening?. this does not comply with SOLID.
    new Vegan() // Why is this happening?. this does not comply with SOLID.
]
queue(p);

TypeScript don't throw an error

我一直在java中进行测试,但是......你可以看到打字稿没有正确抛出错误,我的意思是误报。 我做错了什么?

typescript typescript-typings solid-principles typescript-eslint
1个回答
0
投票

不,你没有错。这里的问题是 TypeScript 识别的是按结构而不是按继承。这称为“结构类型”。

© www.soinside.com 2019 - 2024. All rights reserved.