Here is a TypeScript snippet that compiles just fine (using 1.5.3).
function alertNumber(a: number) {
alert(a + 1);
}
var x:any = "string";
alertNumber(x);
How is it possible that a function requesting parameter of a certain type can be called with argument of type any
?
When you call a function in JavaScript, you can pass in any number of arguments, regardless of what the function declaration specifies. There is no function parameter limit. In the above function, if we pass any number of arguments, the result is always the same because it will take the first two parameters only.
Similar to JavaScript, to pass a function as a parameter in TypeScript, define a function expecting a parameter that will receive the callback function, then trigger the callback function inside the parent function.
any. ❌ Don't use any as a type unless you are in the process of migrating a JavaScript project to TypeScript. The compiler effectively treats any as “please turn off type checking for this thing”. It is similar to putting an @ts-ignore comment around every usage of the variable.
Specifying Type Arguments TypeScript can usually infer the intended type arguments in a generic call, but not always. For example, let’s say you wrote a function to combine two arrays: function combine < Type > (arr1: Type [], arr2: Type []): Type [] {
Summary: in this tutorial, you will learn about the TypeScript function types that allow you to define types for functions. A function type has two parts: parameters and return type. When declaring a function type, you need to specify both parts with the following syntax:
Types of TypeScript variables can be explicitly set using annotations. Here is a TypeScript variable that is of string type. Using the same annotation syntax, we can define the types of function arguments and return value. Here is a function that adds two numbers. Above function can also be used to concatenate 2 strings.
The TypeScript compiler throws an error if the type of the param passed isn’t a number. The number and type of arguments can vary when calling certain JavaScript functions. An example would be writing a function that returns a user from either an ID (one argument) or phone number (one argument), or a combination of address and name (two arguments).
It's because you opt out of type-checking when you use any
types.
[Sometimes] we want to opt-out of type-checking and let the values pass through compile-time checks. To do so, we label these with the 'any' type. - Handbook
To avoid troubles with any
:
--noImplicitAny
compiler option (or turn off Allow implicit any types
in Visual Studio).any
types except where necessary (Ex. var x: any
)If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With