简体   繁体   English

检查 object 是否属于类型(类型定义为数组) - TypeScript

[英]Check if object is of type (type is defined as array) - TypeScript

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我想写一些东西来检查 object 是否是 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]);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM