gpt4 book ai didi

javascript - Typescript 中的编译错误

转载 作者:行者123 更新时间:2023-12-03 07:20:08 28 4
gpt4 key购买 nike

我是 Typescript 新手。

我今天编写了下面的代码,但在编辑器中出现了编译错误。

Type 'EngineFactory' is not assignable to type 'EngineInterface'. Property 'run' is missing in type 'EngineFactory'.

我明白此错误消息的含义,但我不知道如何修复此错误。请教我修复此错误的适当方法。

interface EngineInterface {

run();

}


class HondaEngine implements EngineInterface{

constructor() {}

run() {}

}


class ToyotaEngine implements EngineInterface{

constructor() {}

run() {}

}

enum EngineType {

Honda,
Toyota

}


class EngineFactory {

constructor(engineType: EngineType){

if (engineType === EngineType.Honda) {
return new HondaEngine();
}

if (engineType === EngineType.Toyota) {
return new ToyotaEngine();
}

}

}



class Car {

private engine: EngineInterface;

constructor(engineType: EngineType) {
this.engine = new EngineFactory(engineType);
}

}



let car = new Car(EngineType.Toyota);

注意

按照下面的方式编写代码不会产生编译错误。但我想知道是否有另一种方法可以修复我上面粘贴的错误。

class EngineFactory {

constructor(){}

static getEngine(engineType: EngineType): EngineInterface {

if (engineType === EngineType.Honda) {
return new HondaEngine();
}

if (engineType === EngineType.Toyota) {
return new ToyotaEngine();
}
}
}

class Car {

private engine: EngineInterface;

constructor(engineType: EngineType) {
this.engine = EngineFactory.getEngine(engineType);
}

}


let car = new Car(EngineType.Toyota);

我希望我可以在构造函数方法中定义返回类型...

class EngineFactory {

// Typescript won't let me define returned type in constructor.
constructor(engineType: EngineType): EngineInterface{

if (engineType === EngineType.Honda) {
return new HondaEngine();
}

if (engineType === EngineType.Toyota) {
return new ToyotaEngine();
}

}

}

最佳答案

  1. 在构造函数中返回对象是没有意义的。
  2. 这样写代码会更清晰:

    类引擎工厂{ 构造函数(){}

    static getEngine(engineType: EngineType): EngineInterface {
    switch(EngineType):
    //case ....
    }

    }

关于javascript - Typescript 中的编译错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36243653/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com