你好我試圖基本上繼承Vehicle類中的Car類而不使用extends. 我想這樣做是因為我正在制作瀏覽器擴展并且我無權訪問該類,但我可以訪問該實體。這按預期作業,但打字稿在 Car 類行上拋出錯誤
Class 'Car' incorrectly implements interface 'ICar'.
Type 'Car' is missing the following properties from type 'ICar': steer, accelerate, brake
如果代碼按我預期的那樣作業,它應該注銷“轉向”并"Honking"
https://www.typescriptlang.org/playground/CarExample
interface IVehicle {
steer(): void;
accelerate(): void;
brake(): void;
}
interface ICar extends IVehicle {
honk(): void;
}
class Vehicle implements IVehicle {
constructor(){
console.log("Vehicle created");
}
steer(): void {
console.log("Steering");
}
accelerate(): void {
console.log("Accelerating");
}
brake(): void {
console.log("Braking");
}
}
class Car implements ICar {
constructor(veh: IVehicle){
Object.setPrototypeOf(this, Object.getPrototypeOf(veh));
Object.assign(this, veh);
// Even with the two lines above, it is saying that the object is missing the methods, "steer", "accelerate", and "brake"
}
honk(): void {
console.log("Honking");
}
}
const veh = new Vehicle();
const car = new Car(veh);
console.log(car.steer());
console.log(car.honk());
uj5u.com熱心網友回復:
您需要創建一個Car擴展的介面IVehicle
interface IVehicle {
steer(): void;
accelerate(): void;
brake(): void;
}
interface ICar extends IVehicle {
honk(): void;
}
class Vehicle implements IVehicle {
constructor() {
console.log("Vehicle created");
}
steer(): void {
console.log("Steering");
}
accelerate(): void {
console.log("Accelerating");
}
brake(): void {
console.log("Braking");
}
}
interface Car extends ICar { } // <----------- SEE THIS CHANGE
class Car {
constructor(public veh: IVehicle) {
Object.setPrototypeOf(this, Object.getPrototypeOf(veh));
Object.assign(this, veh);
// Even with the two lines above, it is saying that the object is missing the methods, "steer", "accelerate", and "brake"
}
honk(): void {
console.log("Honking");
}
}
const veh = new Vehicle();
const car = new Car(veh);
console.log(car.steer()); // ok
console.log(car.honk()); // ok
操場
它被稱為宣告合并
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/530885.html
標籤:打字稿目的哎呀原型
