Using type Annotations in Typescript Functions

I am starting to move to Typescript. I discover how works type annotations in typescript functions.
Let start by showing a few things I learned today about Typescript.
Typescript allows type annotation in function parameters and returns types.
Types in Function parameters.
The default type for the parameters in functions is any. Use: type after the declaration to set the style.
function Authentication(user:string, age:Number) {
}
Types in functions the return type
The return type in functions allows set primitive, build-in types or custom types as a return type.
Use the void type for functions without a return value.
function isValid(user:string, age:Number) : boolean {
return true;
}
function removeCookies(user:string, age:Number) : void {
}
Another excellent Typescript features are the optional and default parameters.
Optional parameter
Use optional parameters in functions are set adding a ? to the end of parameter declaration.
function authentication(user:string, age?:Number, save) : boolean {
return true;
}
authentication("dany") //no compiler error.
The default parameters value
If not passes the parameter to the function, it set a default value of 32 to it.
function authentication(user:string, age:Number = 32, save) : boolean {
return age > 30
}
Finish
Thanks for reading my small recap about using annotation types with Typescript in functions. If you enjoyed it, please share.
Photo by Max Delsid on Unsplash
Related Articles
Using Typescript Types
Typescript comes with its types, and each one is part of typescript, not javascript. Typescript will provide these types as part of our development process, notify the compiler of the data type used, and force us to implement them appropriately. Tupl...
How to Test Errors with Jest in Typescript
I'm continuing with Jest and typescript, we already know how to expect and assert variables and objects in our code, next step is handling errors. The Calculator has a new requirement if the type of calculation is not +,- or / we need to throw an err...
Real Software. Real Lessons.
I share the lessons I learned the hard way, so you can either avoid them or be ready when they happen.
Join 13,800+ developers and readers.
No spam ever. Unsubscribe at any time.