When testing out my code snippet on the playground for Typescript, an error appears on line 24.
I discovered that the issue can be resolved by explicitly casting commands back to <IPlan[]>
, but I wonder why this extra step is necessary.
Property 'commands' in type 'Thing' cannot be assigned to the same property in base type 'AbstractThing'.
Type '{ plan: number; }[]' cannot be assigned to type 'IPlan[]'.
Type '{ plan: number; }' cannot be assigned to type 'IPlan'.
The types of the 'plan' property are incompatible.
Type 'number' cannot be assigned to type '0 | 10 | 20'.
(property) Thing.commands: { plan: number; }[]
Below is the code snippet:
interface IPlan {
plan: 0 | 10 | 20;
}
// This works
let obj: IPlan = {
plan: 0
};
// Also works
let commands: IPlan[] = [
{
plan: 10
}
];
// Does not work
abstract class AbstractThing {
commands?: IPlan[];
}
class Thing extends AbstractThing {
// The error occurs on this line
commands = [
{
plan: 10
}
]
}