Reputation: 3347
Most likely it must be a very simple issue, but i can't understand why i can't initialize a class instance with enum parameter.
Error: Argument type {type: MessageTypes} is not assignable to parameter type MessageTypes
class:
export enum MessageTypes {
STATUS,
CONTROL
}
export enum MessageStatus {
OK,
ERROR
}
export enum MessageCommands {
REQUEST_STATUS_ALL
}
export class Message {
type: MessageTypes;
status?: MessageStatus;
command?: MessageCommands;
body?: any;
constructor(type: MessageTypes, command?: MessageCommands, status?: MessageStatus, body?: any) {
this.type = type;
this.status = status;
this.command = command;
this.body = body;
}
}
usage:
const msg = new Message({type: MessageTypes.CONTROL});
Upvotes: 0
Views: 460
Reputation: 142947
It looks like you want your constructor to accept an object containing a type
property:
constructor(settings : { type: MessageTypes, command?: MessageCommands, status?: MessageStatus, body?: any}) {
this.type = settings.type;
this.status = settings.status;
this.command = settings.command;
this.body = settings.body;
}
Either that or don't pass in an object, and just pass the type as the first argument.
const msg = new Message(MessageTypes.CONTROL);
If you want to skip some of the arguments, you can just pass in null
or undefined
for the arguments that you don't need:
const msg = new Message(MessageTypes.CONTROL, null, MessageStatus.OK)
Upvotes: 2