If you want to declare Return Types for Functions in TypeScript? Below 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.
1 2 3 4 5 6 7 8 9 10 11 12 | 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:
1 2 3 | greet() : number { return "Hello, " + this.greeting; } |
If you like this question & answer and want to contribute, then write your question & answer and email to freewebmentor[@]gmail.com. Your question and answer will appear on FreeWebMentor.com and help other developers.