[typescript] How to declare Return Types for Functions in TypeScript

I checked here https://github.com/Microsoft/TypeScript/blob/master/doc/spec.md which is the TypeScript Language Specifications but I couldn't see one thing that 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 see we can use something (name:string) => any but they are used mostly when passing callback functions around:

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

This question is related to typescript

The answer is


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;
}

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

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

functionName() : ReturnType { ... }

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.';
}