DEV Community

Cover image for Using type Annotations in Typescript Functions.
Dany Paredes
Dany Paredes

Posted on • Updated on

Using type Annotations in Typescript Functions.

I am starting to move to Typescript. I discover how works type annotations in typescript functions.

Let start to show a few things 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 type.

function Authentication(user:string, age:Number) {
}

Enter fullscreen mode Exit fullscreen mode

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 {

}

Enter fullscreen mode Exit fullscreen mode

Another nice Typescript features are the optional and default parameters.

Optional parameter

The optional parameters can be set as optional adding a ? to the end of parameter declaration.

function authentication(user:string, age?:Number, save) : boolean {
return true;
}
authentication("dany") //no compiler error.

Enter fullscreen mode Exit fullscreen mode

The default parameters value

If the parameter is not passed it set a default value

function authentication(user:string, age:Number = 32, save) : boolean {
  return age > 30
}

Enter fullscreen mode Exit fullscreen mode

That's it!

This was a small recap about how to use annotation types with typescript in functions If you enjoyed please share.

Photo by Max Delsid on Unsplash

Top comments (0)