0

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

1 Answer 1

2

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]);
}
Sign up to request clarification or add additional context in comments.

4 Comments

You can just directly return all of those conditions infixed by && if you invert the first two.
You seem to have deleted your last comment in between my reading it and preparing this playground link to send in response to it: tsplay.dev/W4yMAw
Yeah, i deleted it because it was just an opinion question, so it doesn't really matter. Thanks for the feedback!
Thanks Nicholas, I'll just stick to that for now then. Maybe if I get around to it and it's not too complex, I can write an auto-generator :D

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.