Exploring the use of union types with basic primitives and custom objects, I created a contrived example inspired by the sample union type shown in the Typescript documentation under the Union Types section. In this example, I introduced a fictional type called PaddingLeft:
type PaddingLeft = {
aNumber: string,
}
function padLeft(value: string, padding: string | number | PaddingLeft) {
if (typeof padding === "object") {
return padding.aNumber + value;
}
if (typeof padding === "number") {
return Array(padding + 1).join(" ") + value;
}
if (typeof padding === "string") {
return padding + value;
}
throw new Error(`Expected string or number, got '${padding}'.`);
}
To use the padLeft function, you can call it like this:
padLeft('1', 1);
padLeft('1', '2');
padLeft('1', {aNumber: '34'});
While the implementation of padLeft satisfies Typescript, I aim to avoid using typeof checks such as:
if (typeof padding === "object") {
My goal is to encapsulate the object check inside a function to allow for additional checks beyond a simple typeof verification. Initially, I attempted to create a function that mimics the typeof check but within a function:
function isObjectCheck (args: any) {
return (typeof args === 'object');
}
Subsequently, I tried to replace the typeof check with a call to isObjectCheck (substituting the initial line of the padLeft function):
if (isObjectCheck(padding)) {
Yet, this modification led to Typescript raising an error:
Property 'aNumber' does not exist on type 'string | number | PaddingLeft'. Property 'aNumber' does not exist on type 'string'.
How can I refactor the object check using a function while satisfying Typescript's validation requirements?