Skip to content

Instantly share code, notes, and snippets.

@Kielan
Last active November 22, 2022 05:02
Show Gist options
  • Save Kielan/b99f42dc629b7d4aad459785e57040b2 to your computer and use it in GitHub Desktop.
Save Kielan/b99f42dc629b7d4aad459785e57040b2 to your computer and use it in GitHub Desktop.
JavaScript type checking from react-spring
interface Lookup<T = any> {
[key: string]: T
}
type IsType<U> = <T>(arg: T & any) => arg is Narrow<T, U>
type Narrow<T, U> = [T] extends [Any] ? U : [T] extends [U] ? Extract<T, U> : U
type PlainObject<T> = Exclude<T & Lookup, Function | readonly any[]>
const is = {
arr: Array.isArray as IsType<readonly any[]>,
obj: <T extends any>(a: T & any): a is PlainObject<T> =>
!!a && a.constructor.name === 'Object',
fun: ((a: unknown) => typeof a === 'function') as IsType<Function>,
str: (a: unknown): a is string => typeof a === 'string',
num: (a: unknown): a is number => typeof a === 'number',
und: (a: unknown): a is undefined => a === undefined,
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment