Reputation: 24572
I have this function:
network = (action: boolean): void => {
if (action) {
this.action = action;
this.net = true;
this.netd = true;
} else {
this.action = null;
this.net = false;
this.netd = false;
}
}
Is there a way that I can define in typescript that the action can have a value of boolean OR string?
Upvotes: 2
Views: 6366
Reputation: 740
You can use the |
and do the following:
const network = (action: boolean | string): void => {
if(typeof action === 'string'){
// do something
} else {
// do something else
}
}
Upvotes: 2
Reputation: 23692
You have to get the parameter type in the classic JavaScript way:
network = (action: any): void => {
if (typeof action === 'string')
// action is a string
else
// action is a boolean
}
In order to declare the valid types, functions can be overloaded :
function myFunc(action: boolean): void;
function myFunc(action: string): void;
function myFunc(action: any): void {
if (typeof action === 'string')
// action is a string
else
// action is a boolean
}
myFunc('abc'); // ok
myFunc(false); // ok
myFunc(123); // error
Upvotes: 2
Reputation: 275927
Yes. Just use a function
instead of var
:
function network(action:boolean):void;
function network(action:string):void;
function network(action: any): void {
if (action) {
this.action = action;
this.net = true;
this.netd = true;
} else {
this.action = null;
this.net = false;
this.netd = false;
}
}
network(''); //okay
network(true); // okay
network(12); // ERROR!
Its called function overloading and you can do this for member functions as well.
Upvotes: 2
Reputation: 7135
I don't believe you can for a function declared and assigned to a variable like that, no; Typescript overloads only apply to class methods or regular functions.
Upvotes: 0