I wrote a Typescript function where my argument could be either a string's array or a raw object.
its prototype is:
export const myFunction = async (line: string[] | myCustomType, config: any): Promise<String> => {
if (line?.length < 2)
//line is a string[]
else
//line is a mysCustomType
}
Where myCustomType
is a raw object with a lot of properties / method.
In JavaScript I would have just tried to access to line?.length
and if it would have been undefined
I would have treated line
like an instance of myCustomType
(because myCustomType
doesn't have length
properties.
an array being an object, I already created a method in the Object class allowing me to directly differences the two type:
declare global {
interface Object {
isCustom(): boolean;
}
}
Object.prototype.isCustom = function () {
return false;
};
Where the method isCustom
already exist in type myCustomType
and doesn't return false
. So I can differencies line
's type, but the typescript doesn't allow me to compile.
Property 'length' does not exist on type 'string[] | myCustomType'.
Property 'length' does not exist on type 'myCustomType'
Shall I declare line
's type to be of Object
and use my isCustom()
method ? or is it uggly ?
Any ideas to get rid of this problem ?