-
Notifications
You must be signed in to change notification settings - Fork 7
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Add "isRecord(key, value)" typeguard #4
Comments
This seems to work: function isRecord<K extends string | number, V> (keyGuard: tg.Guard<K>, valueGuard: tg.Guard<V>) {
const fn: any = (input: any): boolean => {
if (typeof input != 'object') return false
return Object.keys(input).every(key => {
const value = input[key]
return keyGuard(key) ? valueGuard(value) : false
})
}
return fn as tg.Guard<Record<K, V>>
} |
The issue here is that it won't properly validate when enums are given as keys; it's impossible with the above signature. We can check if some key is of wrong value, but we cannot check if some is missing. const isFoo = isRecord(isEnum('a', 'b', 'c'), tg.isNumber)
// correct behavior:
isFoo({a: 0, b: 1, c: 2}) // correct type, returns true
isFoo({a: 0, b: 1, c: 2, d: 3}) // wrong type, returns false because `d` doesn't satisfy key guard
isFoo({a: 0, b: 1, c: 'c'}) // wrong type, returns false
// incorrect behavior:
isFoo({a: 0, b: 1}) // wrong type, returns true
isFoo({}) // wrong type, returns true We cannot detect that something is missing because we only have a function for the key. We'd need an actual array, so the guard needs to be split into two internal functions: isRecord<K, V> (keyGuard: Guard<K>, valueGuard: Guard<V>)
isRecord<K, V> (keys: K[], valueGuard: Guard<V>) Unfortunately, it would still be easy to make a mistake and pass in the enum guard, but I can't come up with anything to fix that. |
I guess something like this: function isRecordEnum <K extends string | number, V> (keys: K[], valueGuard: tg.Guard<V>) {
const fn: any = (input: unknown): boolean => {
const keyGuard = tg.isEnum(...keys)
const areAllPresentCorrect = isRecord(keyGuard, valueGuard)
if (!areAllPresentCorrect(input)) return false
return keys.length == Object.keys(keys).length
}
return fn as tg.Guard<Record<K, V>>
} |
No description provided.
The text was updated successfully, but these errors were encountered: