typescript推断
serverMessage
正确地作为
ServerInformation
在以下情况下:
export interface IServerResponse {
type: 'response';
cmd: string;
}
export interface ServerError {
type: 'error',
errorcode: string;
cmd?: string;
trans_id?: string;
data?: Object;
}
export interface ServerInformation {
type: 'information',
info: string;
data?: Object;
}
export type ServerMessage = IServerResponse | ServerError | ServerInformation;
let serverMessage = message as ServerMessage;
switch (serverMessage.type) {
case 'information':
const information: Information = serverMessage.info; // type is inferred correctly
break;
但在我看来,它更符合我在其他地方用来扩展不同类型消息的类语法。
IServerMessage
比把它们组合成
ServerMessage
类型:
能做到吗?我在下面的尝试失败。
export interface IServerMessage {
type: string;
}
export interface IServerResponse extends IServerMessage {
type: 'response';
cmd: string;
}
export interface ServerError extends IServerMessage {
type: 'error',
errorcode: string;
cmd?: string;
trans_id?: string;
data?: Object;
}
export interface ServerInformation extends IServerMessage {
type: 'information',
info: string;
data?: Object;
}
let serverMessage: IServerMessage = message ;
switch (serverMessage.type) {
case 'information':
const information: Information = serverMessage.info; // type is still inferred as ServerMessage, not the more specific InformationMessage
break;