The functions in Typescript

The functions in Typescript

Understand the functions in Typescript

The Typescript language understands the functions return type by default; for example, in the following example, the compiler understands one return boolean and the other is void.

function Auth() {
  return true
}

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

Using return types

Typescript allows setting primitive or Typescript types for function signatures in the return Type. To assign the type, use: at the end of parameters.

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

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

void type

We use the void type when a function doesn't return any value, as the following example.

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

Using function as type

The function is a type in Typescript that is helpful 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 a type function and has an internal procedure to show a message; the login process returns a single value and returns the onComplete.

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 assign another function to the onComplete function.

"`javascript 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")


```node
[nodemon] starting `node .\app.js`
Please go to  /home

The function userLogin executes the code, and the callback function is onComplete and works.

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

The return of Authentication returns a single parameter. What happens if we assign a function that expects two parameters like appleSignIn?

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

Damm!! The function type only checks if is a function doesn't match the number parameters or the return type.

It uses an arrow function force to assign a function that fits with the signature and return.

Change the function type to an arrow function with the return type. Another solution, if you don't want to use an arrow function in the definition, is to create your 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 make the compiler force assign a function that fits with the parameters.

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

Photo by Claudio Guglieri on Unsplash