Jerko Steiner fb41c2ce69 Add @rondo.dev/common guard fn
This is to help guard against types that can be undefined since the
recommended eslint rules recommend against using `!` operator on values
like:

    const obj: Obj | undefined = ...
    obj!.value

Now we can use:

    const obj: Obj | undefined = ...
    const obj2: Obj = guard(isDefined, obj)
    obj.value

The guard function will throw an error if obj parameter is undefined.
2019-09-15 11:40:31 +07:00

36 lines
695 B
TypeScript

type CheckType<T> = (t: unknown) => t is T
export function guard<Expected>(
checkType: CheckType<Expected>,
t: unknown,
): Expected {
if (!checkType(t)) {
throw new Error(
`Value ${t} does not satisfy constraint: ${checkType.name}`)
}
return t
}
export function isUndefined(t: unknown): t is undefined {
return t === undefined
}
export function isNull(t: unknown): t is null {
return t === null
}
export function isDefined<T>(
t: unknown,
): t is T {
return t !== undefined && t !== null
}
export function isNumber(t: unknown): t is number {
return typeof t === 'number'
}
export function isString(t: unknown): t is string {
return typeof t === 'string'
}