首页 > 解决方案 > 在打字稿中传递参数的另一种方法

问题描述

我有一个打字稿类和一个方法。此方法采用三个参数。

class MyClass {

 public static carStatus(name : string , color : string , isReady : boolean){
    let result = isReady ? 'is ready' : 'is not ready';
    return `${color} ${name} ${result}.`;
 }
}

let carStatus = MyClass.carStatus('pride' , 'white' , true);
console.log(carStatus);

我想将(isReady)括号中的第三个参数设置为方法。我知道可以通过这种方式完成:

class MyClass {

public static isReady : boolean;

  public static carStatus(name : string , color : string){
    let result = this.isReady ? 'is ready' : 'is not ready';
    return `${color} ${name} ${result}.`;
  }
}

MyClass.isReady = false;
let carStatus = MyClass.carStatus('pride' , 'white');
console.log(carStatus);

还有另一种方法可以做到这一点吗?

标签: javascripttypescripttypescript-class

解决方案


我相信最简单的方法是使用单独的方法来设置isReady值和没有静态方法的单个CarStatus类:

class CarStatus {
    private isReady: boolean;

    constructor(private name: string, private color: string) {
        this.name = name;
        this.color = color;
    }

    public setReady() {
        this.isReady = true;
    }

    public getStatus(): string {
        let result = this.isReady ? 'is ready' : 'is not ready';
        return `${this.color} ${name} ${result}.`;
    }
}

let carStatus = new CarStatus("pride", "white");
carStatus.setReady();
console.log(carStatus.getStatus());

如果您认为每个概念都不是必需的或可以在不同时间设置,您也可以使用流利的方法。视情况而定,这可能是一种矫枉过正,举个例子:

class CarStatus {  
    constructor(private name: string, private color: string, private isReady: boolean) {
        this.name = name;
        this.color = color;
        this.isReady = isReady;
    }

    public getStatus(): string {
        let result = this.isReady ? 'is ready' : 'is not ready';
        return `${this.color} ${name} ${result}.`;
    }
}

class CarStatusBuilder {
    private name: string;
    private color: string;
    private isReady: boolean;

    public SetReady(): CarStatusBuilder {
        return new CarStatusBuilder() { this.isReady = true};
    }

    public WithName(name: string): CarStatusBuilder {
        this.name = name;
        return this;
    }

    public WithColor(color: string): CarStatusBuilder {
        this.color = color;
        return this;
    }

    public Build(): CarStatus{
        return new CarStatus(this.name, this.color, this.isReady);
    }
}

let carStatus = new CarStatusBuilder()
    .WithColor("white")
    .WithName("pride")
    .Build();
console.log(carStatus.getStatus());

推荐阅读