TypeScript - String Enum for Checking Value Type
11/14/2021, SunRamda's Type Check
Ramda's type checking returns a string, but in order for this to be useful, one needs to know if the returned value matches your intended assertion.
R.type({}); //=> "Object"
R.type(1); //=> "Number"
R.type(false); //=> "Boolean"
R.type('s'); //=> "String"
R.type(null); //=> "Null"
R.type([]); //=> "Array"
R.type(/[A-z]/); //=> "RegExp"
R.type(() => {}); //=> "Function"
R.type(undefined); //=> "Undefined"
Although there is a is
function in Ramda that replicates the behavior of the example, the following will describe how a string enum will be used to replicate the is
function (do use Ramda's built-in is
function as it is more succinct).
The goal is to wrap Ramda's type check in a comparison function to perform the assertion for us. Create a string enum which will be used inside the function to check against Ramda's string return from the type check.
// typeCheck.ts
import { type as checkType } from 'ramda';
// String enum
export enum stringTypes {
'Object',
'Number',
'Boolean',
'String',
'Null',
'Array',
'RegExp',
'Function',
'Undefined'
}
// checkType is R.type which returns a string to explain the checked value type that will be compared against the enum string
export function typeCheck(val: any, type: stringTypes): boolean {
return checkType(val) === stringTypes[type];
}
Usage of the wrapped Ramda value type checking function.
import { typeCheck, stringTypes } from './type-check';
if (typeCheck(folderName, stringTypes.Undefined)) {
// do something here
}