Skip to content

Instantly share code, notes, and snippets.

@laurencestokes
Created March 30, 2023 15:19
Show Gist options
  • Save laurencestokes/1db07e4cad97881dc4480f1dfd2e5a06 to your computer and use it in GitHub Desktop.
Save laurencestokes/1db07e4cad97881dc4480f1dfd2e5a06 to your computer and use it in GitHub Desktop.
axis Type helper in TS
export const typeHelper = (() => {
const types = [
'Array',
'Object',
'String',
'Date',
'RegExp',
'Function',
'Boolean',
'Number',
'Null',
'Undefined',
] as const;
type MethodKeys = `is${typeof types[number] | 'NaN'}`;
const functionObject: Record<MethodKeys, (elem: unknown) => boolean> = {} as Record<
MethodKeys,
(elem: unknown) => boolean
>;
function type(this: unknown) {
return Object.prototype.toString.call(this).slice(8, -1);
}
for (let i = types.length; i--; ) {
functionObject['is' + types[i]] = (function (self: string) {
return function (elem: unknown) {
return type.call(elem) === self;
};
})(types[i]);
}
// Need a special case for NaN for the extra check as NaN is technically a number
// But it's the only number for which it won't equal itself
functionObject['isNaN'] = (function (self: string) {
return function (elem: unknown) {
return type.call(elem) === self && elem !== elem;
};
})('Number');
return functionObject;
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment