【问题标题】:Check if object is of type (type is defined as array) - TypeScript检查对象是否属于类型(类型定义为数组) - TypeScript
【发布时间】:2022-01-25 09:55:08
【问题描述】:

假设我有这个

export type Hash = [ hashtype, hash ];

export type hashtype = -16 | -43 | 5 | 6;
export type hash = Buffer;

我想写一些东西来检查一个对象是否是一个哈希

未实施

isHash = (obj: any) => {
    return (obj is Hash) // pseudo code, to implement
}

这样我才会有这样的回报:

isHash(5)                         => false    //  no hash
isHash([25, <Buffer ad 30>])      => false    //  25 is not in hashType

isHash([5, <Buffer ad 30>])       => true     //  valid

【问题讨论】:

    标签: javascript typescript types interface


    【解决方案1】:

    没有通用的方法来检查类型是否匹配。对于您的具体情况,我会这样做:

    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]);
    }
    

    【讨论】:

    • 如果你反转前两个条件,你可以直接return所有这些由&amp;&amp;中缀的条件。
    • 您似乎删除了您在我阅读它和准备发送此游乐场链接以回复它之间的最后一条评论:tsplay.dev/W4yMAw
    • 是的,我删除了它,因为它只是一个意见问题,所以这并不重要。感谢您的反馈!
    • 谢谢 Nicholas,我现在就坚持下去。也许如果我解决它并且它不是太复杂,我可以编写一个自动生成器:D
    猜你喜欢
    • 2022-01-08
    • 1970-01-01
    • 1970-01-01
    • 2023-04-09
    • 2011-09-26
    • 2011-01-13
    • 1970-01-01
    • 2016-01-14
    • 2013-09-12
    相关资源
    最近更新 更多