The functions in Typescript
Tags: codenewbie, typescript, javascript
Published: 2020-04-06 00:00:00

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.

```javascript
function Auth() {
  return true
}

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

### Using return types

Typescript allows set a primitive or typescript type for function signatures in the return Type. For set, a type in a function add: 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.

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

### void type

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

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

### Using function as type

The function is a type in typescript and can be used 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 function and have an internal function to show a message, the login process returns a single value and is used by onComplete function.

```javascript
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 in onComplete and works.

If we read our code, the function googleSign gets 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?

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

```

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

Using 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 don't want to use an arrow function into the definition create your own type like OnComplete.

```javascript
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 to assign a function that fits with the parameters.

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.

Photo by <a href="https://unsplash.com/@claudioguglieri?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText">Claudio Guglieri</a> on <a href="https://unsplash.com/s/photos/fish?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText">Unsplash</a>