I have defined two types:
export type Ping = {
kind: 'ping',
lag?: number
}
export type Message = {
kind: 'message',
value: string
}
I am receiving a JSON encoded incoming message string:
let msg = "{kind:'message', value: 3 }",
ping = "{kind:'ping'}";
Once I parse this string into an object:
let obj = JSON.parse(msg);
I need to validate these messages to ensure they contain the expected properties and then dispatch them accordingly:
export function isMessage(_: any): _ is Message {
if (typeof _ === 'object') {
let res = (_ as Message);
if (res.kind === 'message' && res.value && typeof res.value === 'string') {
return true;
}
}
return false;
}
export function use(_: any) {
if (isMessage(_)) {
console.log('Message: ', _.value);
}
}
Do I need to manually check every field of each message type like shown above, or is there a simpler method for achieving this?