The functions in Typescript

April 06, 2020

The Typescript language by default inferred into the functions return type. That’s means if the return is a boolean, the return type will be a boolean type or if not have one is void type.

function Auth() {
  return true
}

function Auth() {
  console.log("hello")
}

Using return types

Typescript allow set a primitive or typescript types for funcion signatures in the return Type. For set a type in a function add : in the end of parameters.

The function with the signature will notify to the compiler needs to check the signature of function return code.

function authenticateUser(user: User): boolean {
  return true
}

void type

The void type is used in function with don’t have to return any value and the compiler will check the function code dont have a return.

function logMessage(): void {
  console.log("message completed.")
}

Using function as type

The function is a type in typescript and can be use for variable declaration. it is useful to change actions or behaviors in our code.

For example, we have a class for Authentication, it has a property onComplete type Function.

The property onComplete is type functin and have a internal function to show a message, the login process return a single value and is used by onComplete function.

export default class Authentication {
    public onComplete: Function = this.greetingUser;
    private referralUrl: string = "/home";
    constructor() {}
    private greetingUser(url: string): void {
        console.log(`Thanks! go to ${this.referralUrl}`);
    }
    loginProcess(user: string, password: string) {
        if (user == "dany" && password == "1234") {
            return this.referralUrl;
        }
    }
}

We import Authentication and use it, we asign another function to the onComplete function.

import Authentication from "./Authentication"

class App {
  userLogin(name: string, password: string) {
    let auth = new Authentication()
    auth.onComplete = this.googleSignIn
    auth.onComplete(auth.loginProcess(name, password))
  }

  googleSignIn(url: string): void {
    console.log(`Please go to  ${url}`)
  }

  appleSignIn(user: string, role: string): void {
    console.log(`Hello ${user} , your ${role}`)
  }
}

const app = new App()

app.userLogin("dany", "1234")
[nodemon] starting `node .\app.js`
Please go to  /home

The function userLogin execute the code and the callback function in onComplete and works.

If we read our code, the function googleSign get the parameter return by loginProcess.

The return of Authentication return a single parameter, what happens if we assign a function that expects 2 parameters like appleSignIn?

[nodemon] starting `node .\app.js`
Hello /home , your undefined

Dammm!! The function type only check if is a function dont check the number parameters or the return type.

Using a arrow function force to asign a function that fit with the signature and return.

Change the function type to a arrow function with the return type, another solution if dont want to use a arrow function into the definition create your own type like OnComplete.

type OnCompleteAction = (name: string) => void;
export default class Authentication {
    public onComplete: OnCompleteAction = this.greetingUser;
    private referralUrl: string = "/home";
    constructor() {}
    private greetingUser(): void {
        console.log(`Thanks! go to ${this.referralUrl}`);
    }
    loginProcess(user: string, password: string): string {
        if (user === "dany" && password === "1234") {
            return this.referralUrl;
        }
        return "no access";
    }
}

These changes makes the compiler force to assign a function that fit with the parameters .

function parameter

Hopefully, that will give you a bit of help with Function as Types and return types in Typescript. If you enjoyed this post, share it.