Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why declare an 'any' return type in TypeScript?

Tags:

typescript

For instance:

function getUserInput(input: any): any {
    return input
}

It seems silly to declare "anything can be returned". What's the purpose?

like image 878
mkhira2 Avatar asked Mar 05 '23 16:03

mkhira2


1 Answers

It is useful for the lazy and the ignorant.

But don't take this as a rant !

Sometimes you (or your client / boss) "need" to be lazy on typing. You need to quickly write something when the actual type is too complicated, as already noted in artem's answer.

It could allow flexibility in coding. (though it could lead to a poor code base eventually)

Also, you may very well be completely ignorant of the actual return type of some API call or javascript function that is a black box for you. Maybe it constructs dynamically an object and has dozens of possible return structures.

For instance : how would you type the result of eval function if the (sanitized) input could be a variety of json expressions, or a number, or a string etc?

When you start to write object | number | string | boolean | null, you want to write any instead, for readability.

But of course, you should try to avoid this as much as possible, it is considered bad practice.

Anyway, I think it would complicate things to miss this language feature in certain real-world scenarios.

EDIT : and I nearly forgot, but I think TypeScript must have this feature or a similar one as per its specification : every JavaScript code is supposed to be "valid" TypeScript (the compiler will gladly accept any JS code as TypeScript, and simply turn it as the same JS code, with the correct compiler options).

In such a JS-TS code, most bindings have to be implicitly typed as any to fit this scenario.

like image 92
Pac0 Avatar answered Mar 17 '23 21:03

Pac0