In my Typescript function, I have an argument that can either be an array of strings or a custom object.
The prototype of the function is as follows:
export const myFunction = async (line: string[] | myCustomType, config: any): Promise<String> => {
if (line?.length < 2)
//line is a string[]
else
//line is a myCustomType
}
Here, myCustomType
refers to a raw object with numerous properties and methods.
In JavaScript, I could easily check for line?.length
being undefined and treat it as an instance of myCustomType
because myCustomType
does not have a length
property.
Considering an array as an object, I have created a method in the Object class to differentiate between the two types:
declare global {
interface Object {
isCustom(): boolean;
}
}
Object.prototype.isCustom = function () {
return false;
};
The isCustom
method already exists in the myCustomType
, but TypeScript does not allow me to compile due to the error message:
Property 'length' does not exist on type 'string[] | myCustomType'.
Property 'length' does not exist on type 'myCustomType'
Should I declare the type of line
as Object
and utilize the isCustom()
method? Or is there a better solution to this issue?
Any suggestions on how to resolve this problem?