stack new
stack new

Reputation: 79

How change a function to accept different types as argument

In the below eg, myFoo will accept an argument which is of type Boolean.

function myFoo(value:Boolean) { }

My Questions is, Is it possible to change the myFoo function to accept multiple types using prototype ?

eg, function myFoo(value:Boolean | string) { }

Note: myFoo is a global function, which can't be edited directly.

Updated

Global function which is in different file,

export declare class MyGlobalClass<T> extends Observable<T> implements Observer<any> {
    myFunc(value: Boolean): void;
} 

In my TS file,

this.myGlobalClass.myFunc('string');

But it throws type error. as myFunc accepts only Boolean. I need to fix this.

Upvotes: 0

Views: 64

Answers (2)

ImGroot
ImGroot

Reputation: 836

function myFoo(value: Boolean|string) {
    if (typeof value === 'string') {
        //do string patch
    } else {
        //whatever
    }
}

Upvotes: 1

victor
victor

Reputation: 812

change the type to be "any"

function myFoo(value:any) { }

Note that you will lose all the type checking that Typescript offers for this as you are basically telling Typescript that you want to allow your "value" parameter to literally be any type.

Upvotes: 0

Related Questions