Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cast function parameter type in Typescript

Tags:

typescript

Forcibly change a functions parameter type by casting itself.

It looked like

(<number>foo)(1)

Where

function foo( v : string )
like image 675
user2874932 Avatar asked Jun 30 '26 17:06

user2874932


1 Answers

You can't change the function param types but you can cast (type assert) the param you're passing to it to any:

function fn(obj: string) {
    ...
}

fn(1 as any);

But you can make the function more generic:

function fn(obj: string | number) {
    ...
}

fn(1);
fn("str");

You can also use generics:

function fn<T>(obj: T) {
    ...
}

fn(1);
fn("str");
like image 150
Nitzan Tomer Avatar answered Jul 05 '26 15:07

Nitzan Tomer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!