Dany Paredes
Dany Paredes | Javascript / Web

Dany Paredes | Javascript / Web

Using type Annotations in Typescript Functions

Using type Annotations in Typescript Functions

Type Annotation with Typescript

Dany Paredes's photo
Dany Paredes
·Mar 23, 2020·

2 min read

Subscribe to my newsletter and never miss my upcoming articles

Table of contents

  • Types in Function parameters.
  • Types in functions the return type
  • Optional parameter
  • The default parameters value
  • Finish

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

 
Share this