0

How could I deal with optional parameters in Typescript?

I have the following model:

export class PowerPlant {
  id: number;
  orgName: string;
  minPower: number;
  maxPower: number;
  powerPlantType: string;
  rampRateInSeconds: number;
  rampPowerInKw: number;
}

In this model, the last two fields namely the rampRateInSeconds and rampPowerInKw are going to be optional values and will be there depending on the powerPlantType string. I want to be able to instantiate this in the constructor and in the constructor, I will check the powerPlantType string and if it is of a certain type, I would like to set these 2 additional fields.

Coming from a functional programming background, I would have these 2 types as optional and pattern match on the powerPlantType String and set the 2 values accordingly. How could I achieve the same effect here in Typescript?

joesan
  • 13,963
  • 27
  • 95
  • 232
  • `I want to be able to instantiate this in the constructor and in the constructor,` <= One too many constructors? What did you mean to write? – Igor Aug 25 '17 at 16:53
  • 1
    And what exactly are you stuck on? It's easy enough to find out how to define optional parameters, for example. – jonrsharpe Aug 25 '17 at 16:56
  • Possible duplicate: [How to pass optional parameters in TypeScript while omitting some other optional parameters?](https://stackoverflow.com/a/30734778/1260204). You can use the same pattern for a constructor. – Igor Aug 25 '17 at 17:01
  • Why is this down voted? – joesan Aug 27 '17 at 09:45

1 Answers1

6

You do not need a class if you don't have methods, an interface is sufficient and you can assign object literals to variables that are of the interface type. Interfaces can have optional parameters, and so you don't need to specify all members:

interface PowerPlant {
    id: number;
    orgName?: string;
    minPower?: number;
    maxPower?: number;
    powerPlantType?: string;
    rampRateInSeconds?: number;
    rampPowerInKw?: number;
  }

  var x : PowerPlant = {
      id: 10 
  }

If you want something that feels more like pattern matching you can use discriminated union types and type guards:

interface Square {
    kind: "square";
    size: number;
}

interface Rectangle {
    kind: "rectangle";
    width: number;
    height: number;
}

interface Circle {
    kind: "circle";
    radius: number;
}

type Shape = Square | Rectangle | Circle;

function test1(s: Shape) {
    if (s.kind === "square") {
        s;  // Square
    }
    else {
        s;  // Rectangle | Circle
    }
}

Previous example from here

Titian Cernicova-Dragomir
  • 230,986
  • 31
  • 415
  • 357