Bogdan Tushevskyi
Bogdan Tushevskyi

Reputation: 752

two type variable in type script

I have a function parameter which accepts two types: string | string[]. I am using this parameter for a toaster service which accepts only the string type, so when I am using join(' ') I have got an error: Property 'join' does not exist on type 'string | string[]'. Property 'join' does not exist on type 'string'. and can't compile the application.

showToaster(msg: string, customClass: string | string[]) {
        let cstmClass: any;

        switch (typeof customClass) {
            case 'string':
                cstmClass = customClass;
                break;
            case 'object':
                cstmClass = customClass.join(' ');
                break;
        }

        this.toastrService.show(msg, null, {
            toastClass: cstmClass,
            timeOut: 3500
        });
}

Upvotes: 1

Views: 336

Answers (1)

Mathyn
Mathyn

Reputation: 2620

Use Array.isArray to determine the type:

if(Array.isArray(customClass)) {
    cstmClass = customClass.join(' ');
}
else {
    cstmClass = customClass;
}

The reason for the compile array is that the | option only exposes properties and methods shared by both types. The reason checking if the type is an object does not work is because object does not have the join method.

Upvotes: 1

Related Questions