HiveBrain v1.2.0
Get Started
← Back to all entries
snippetjavascriptCritical

How to declare Return Types for Functions in TypeScript

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
typescriptreturnfunctionstypesdeclareforhow

Problem

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) {
  // ...
}

Solution

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

Code Snippets

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();
greet() : number {
    return "Hello, " + this.greeting;
}

Context

Stack Overflow Q#12736269, score: 194

Revisions (0)

No revisions yet.