Reputation: 1176
I'm new to typescript
export class Reward {
id: number;
point: number;
status: Status;
constructor(id: number, point: number, status: Status) {
this.id = id;
this.point = point;
this.status = Status.NONE;
}
}
export enum Status {
CLAIMED,
AVAILABLE,
NONE
}
public getRewardsOf(numberOfDay: number): Array<Reward> {
return this.availableRewards.map((reward: Reward, index: number) => {
if (index == (numberOfDay - 1)) {
return new Reward(reward.id, reward.point, Status.AVAILABLE);
} else {
return reward;
}
});
}
the if doesn't work for me. It still returns the same old object (the status value is the same). it's supposed to be different even though I create a new object.
It works when I use
if (index == (numberOfDay - 1)) {
return {
'id': reward.id,
'point': reward.point,
'status': Status.AVAILABLE
};
} else {
return reward;
}
if so I lose the power of typescript
Upvotes: 2
Views: 1077
Reputation: 715
Your constructor is hardcoding the value Status.NONE
:
...
this.status = Status.NONE
...
This will effectively discard the status argument passed to the constructor.
If you wish to provide Status.NONE as a default parameter, do:
constructor(id: number, point: number, status = Status.NONE) {
this.id = id;
this.point = point;
this.status = status;
}
You can further reduce this to:
constructor(public id: number, public point: number,
public status = Status.NONE) {
}
Edit: Also, because TypeScript is structurally, not nominally typed (see structural typing), you don't lose any type safety by returning a literal versus a class-constructed instance. Both versions of your code can safely be said to be returning a Reward
.
TS Playground
class Reward {
constructor(public id: string) {}
}
// This is OK.
const x: Reward = {id: '12435'};
If Reward
starts adding methods, then what you lose is the ability to create a Reward
easily with your object literal.
Upvotes: 5