Reputation: 3476
I have a javascript class in a project which I want to convert to typescript:
class PricePlan {
constructor(name, supplier, unitRate, peakTimeMultipliers) {
this.name = name
this.supplier = supplier
this.unitRate = unitRate
this.peakTimeMultipliers = peakTimeMultipliers
}
getPrice(dateTime) {
let peakMultiplier = this.peakTimeMultipliers.find(multiplier => {
return multiplier.day === dateTime.getDay()
});
return peakMultiplier ? peakMultiplier.multiplier : this.unitRate;
}
}
PricePlan.DayOfWeek = Object.freeze({
Sunday:0,
Monday:1,
Tuesday:2,
Wednesday:3,
Thursday:4,
Friday:5,
Saturday:6
})
PricePlan.PeakTimeMultiplier = class {
constructor(dayOfWeek, multiplier) {
this.day = dayOfWeek
this.multiplier = multiplier
}
}
module.exports = PricePlan
I have changed the class to be a typescript class like this:
export class PricePlan {
private name;
private supplier;
private unitRate;
private peakTimeMultipliers
constructor(name, supplier, unitRate, peakTimeMultipliers = false) {
this.name = name
this.supplier = supplier
this.unitRate = unitRate
this.peakTimeMultipliers = peakTimeMultipliers
}
getPrice(dateTime) {
let peakMultiplier = this.peakTimeMultipliers.find(multiplier => {
return multiplier.day === dateTime.getDay()
});
return peakMultiplier ? peakMultiplier.multiplier : this.unitRate;
}
DayOfWeek = {
Sunday: 0,
Monday: 1,
Tuesday: 2,
Wednesday: 3,
Thursday: 4,
Friday: 5,
Saturday: 6
}
PeakTimeMultiplier = class {
private day
private multiplier
constructor(dayOfWeek, multiplier) {
this.day = dayOfWeek
this.multiplier = multiplier
}
}
}
Now there's no compiler error, but the class gets called like this in a test:
let peakTimeMultiplier = new PricePlan.PeakTimeMultiplier(PricePlan.DayOfWeek.Wednesday, 10)
Here I have two errors:
Those are the properties which I moved inside the class. How can I make them visible?
Upvotes: 1
Views: 95
Reputation: 2690
The fastest way to fix your build is to just declare DayOfWeek
and PeakTimeMultiplier
as static
. Sometimes is cleaner to refactor those into a namespace like this:
export class PricePlan {
private name;
private supplier;
private unitRate;
private peakTimeMultipliers
constructor(name, supplier, unitRate, peakTimeMultipliers = false) {
this.name = name
this.supplier = supplier
this.unitRate = unitRate
this.peakTimeMultipliers = peakTimeMultipliers
}
getPrice(dateTime) {
let peakMultiplier = this.peakTimeMultipliers.find(multiplier => {
return multiplier.day === dateTime.getDay()
});
return peakMultiplier ? peakMultiplier.multiplier : this.unitRate;
}
}
export namespace PricePlan {
export const enum DayOfWeek {
Sunday,
Monday,
Tuesday,
Wednesday,
Thursday,
Friday,
Saturday
}
export class PeakTimeMultiplier {
private day
private multiplier
constructor(dayOfWeek, multiplier) {
this.day = dayOfWeek
this.multiplier = multiplier
}
}
}
See that also DayOfWeek
is declared as an enum
Upvotes: 1