很可能它一定是一个非常简单的问题,但我无法理解为什么我无法用枚举参数初始化一个类实例。
错误:Argument type {type: MessageTypes} is not assignable to parameter type MessageTypes
类:
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;
}
}
用法:
const msg = new Message({type: MessageTypes.CONTROL});
答案 0 :(得分:2)
看起来您希望构造函数接受包含type
属性的对象:
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;
}
要么传入或不传入对象,只要将类型作为第一个参数传递。
const msg = new Message(MessageTypes.CONTROL);
如果你想跳过一些参数,你可以传入null
或undefined
来获取你不需要的参数:
const msg = new Message(MessageTypes.CONTROL, null, MessageStatus.OK)