[英]Check if object is of type (type is defined as array) - TypeScript
假設我有這個
export type Hash = [ hashtype, hash ];
export type hashtype = -16 | -43 | 5 | 6;
export type hash = Buffer;
我想寫一些東西來檢查 object 是否是 Hash
未實現
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
沒有一種通用的方法來檢查類型是否匹配。 對於您的具體情況,我會這樣做:
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.