Within my Angular project, I am faced with an object that includes a type and status field where the status can change depending on the type. While some might argue that this is not the best design practice, it is how things are currently structured in my project. The issue I am encountering is that I am unable to utilize the spread operator on this object due to the compiler displaying an error message stating
Property 'getStatusList' is missing in type ...
.
To simplify, the class structure is similar to the following:
export class Foo {
constructor(
public type: number,
public status: number
) { }
getStatusList(): string[] {
switch (this.type) {
case 3: {
return ['Off', 'Interval', 'On Hold']
}
default: {
return ['Off', 'On']
}
}
}
}
This situation arises with TypeScript version 2.9.2 and angular cli version 6.1.1
The code snippet below triggers the aforementioned error. However, while experimenting with sample code in TypeScript Playground, I realized that perhaps using Object.assign could be a solution. Yet, I initially believed that I could easily modify certain properties of an object using the spread operator.
const oldFoo: Foo = new Foo(3, 5);
console.log('old status: ', oldFoo.status);
const newFoo: Foo = { ...oldFoo, type: 1, status: 7 };
console.log('new status: ', newFoo.status);