How to declare Return Types for Functions in TypeScript

JavascriptTypescriptOop

Javascript Problem Overview


I checked here https://github.com/Microsoft/TypeScript/blob/master/doc/spec.md which is the TypeScript Language Specifications but I couldn't find how I can declare a return type of the function.

I showed what I was expecting in the code below: greet(name:string): string {}

class Greeter {
  greeting: string;
  constructor(message: string) {
    this.greeting = message;
  }
  greet(): string {
    return "Hello, " + this.greeting;
  }
}

I know I can use (name:string) => any but this is used mostly when passing callback functions around:

function vote(candidate: string, callback: (result: string) => any) {
  // ...
}

Javascript Solutions


Solution 1 - Javascript

You are correct - here is a fully working example - you'll see that var result is implicitly a string because the return type is specified on the greet() function. Change the type to number and you'll get warnings.

class Greeter {
    greeting: string;
    constructor (message: string) {
        this.greeting = message;
    }
    greet() : string {
        return "Hello, " + this.greeting;
    }
} 

var greeter = new Greeter("Hi");
var result = greeter.greet();

Here is the number example - you'll see red squiggles in the playground editor if you try this:

greet() : number {
    return "Hello, " + this.greeting;
}

Solution 2 - Javascript

Return types using arrow notation is the same as previous answers:

const sum = (a: number, b: number) : number => a + b;

Solution 3 - Javascript

functionName() : ReturnType { ... }

Solution 4 - Javascript

You can read more about function types in the language specification in sections 3.5.3.5 and 3.5.5.

The TypeScript compiler will infer types when it can, and this is done you do not need to specify explicit types. so for the greeter example, greet() returns a string literal, which tells the compiler that the type of the function is a string, and no need to specify a type. so for instance in this sample, I have the greeter class with a greet method that returns a string, and a variable that is assigned to number literal. the compiler will infer both types and you will get an error if you try to assign a string to a number.

class Greeter {
	greet() {
		return "Hello, ";  // type infered to be string
	}
} 

var x = 0; // type infered to be number

// now if you try to do this, you will get an error for incompatable types
x = new Greeter().greet(); 

Similarly, this sample will cause an error as the compiler, given the information, has no way to decide the type, and this will be a place where you have to have an explicit return type.

function foo(){
	if (true)
		return "string"; 
	else 
		return 0;
}

This, however, will work:

function foo() : any{
	if (true)
		return "string"; 
	else 
		return 0;
}

Solution 5 - Javascript

External return type declaration to use with multiple functions:

type ValidationReturnType = string | boolean;

function isEqual(number1: number, number2: number): ValidationReturnType {
    return number1 == number2 ? true : 'Numbers are not equal.';
}

Solution 6 - Javascript

tldr;

getUserRole(name: string) {
   const roles: Role[] = [{ name: 'admin' }, { name: 'admin' }]
   return roles.find(role => role.name === name) || null;
}


let userRole: ReturnType<typeof getUserRole>; // as type of Role | null

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionTarikView Question on Stackoverflow
Solution 1 - JavascriptFentonView Answer on Stackoverflow
Solution 2 - JavascriptAdverblyView Answer on Stackoverflow
Solution 3 - JavascriptLuca C.View Answer on Stackoverflow
Solution 4 - Javascriptmohamed hegazyView Answer on Stackoverflow
Solution 5 - JavascriptC.R.B.View Answer on Stackoverflow
Solution 6 - JavascriptcagcakView Answer on Stackoverflow