Let's say I have this
export type Hash = [ hashtype, hash ];
export type hashtype = -16 | -43 | 5 | 6;
export type hash = Buffer;
I want to write something that will check whether an object is a Hash
not implemented
isHash = (obj: any) => {
return (obj is Hash) // pseudo code, to implement
}
So that I would have such a return:
isHash(5) => false // no hash
isHash([25, <Buffer ad 30>]) => false // 25 is not in hashType
isHash([5, <Buffer ad 30>]) => true // valid
There isn't a general-purpose way to check whether a type matches. For your specific case, I would do something like this:
const isHash = (obj: unknown): obj is Hash => {
if (!Array.isArray(obj)) {
return false;
}
if (obj.length !== 2) {
return false;
}
return [-16, -43, 5, 6].includes(obj[0]) && Buffer.isBuffer(obj[1]);
}