Background
I'm making type checking function with typescript.
const checkType = <T>(value: unknown, isTypeFn: (value: unknown) => value is T): T => {
if (!isTypeFn(value)) {
console.error(`${isTypeFn} ${value} does not have correct type`);
throw new Error(`${value} does not have correct type`);
}
return value;
};
const isBoolean = (value: unknown): value is boolean => typeof value === 'boolean';
const isString = (value: unknown): value is string => typeof value === 'string';
const isNumber = (value: unknown): value is number => typeof value === 'number';
const isNull = (value: unknown): value is null => value === null;
And I can use it like below.
const a = await getNumber() // this should be number
const numA: number = checkType(a, isNumber); // numA is number or throw Error!
Problem
I want to extend the checkType function like below.
const b = await getNumberOrString();
const bNumOrString: number | string = checkType(b, isNumber, isString);
const bNumOrBoolean: number | boolean = checkType(b, isNumber, isBoolean);
const bStringOrNull: string | null = checkType(b, isString, isNull);
How to improve the checkType for it to work like this ?
checkType(b, (a) => isNumber(a) || isString((a))