How to declare Return Types for Functions in TypeScript

后端 未结 4 1305
花落未央
花落未央 2020-12-13 17:05

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 d

相关标签:
4条回答
  • 2020-12-13 17:07
    functionName() : ReturnType { ... }
    
    0 讨论(0)
  • 2020-12-13 17:12

    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;
    }
    
    0 讨论(0)
  • 2020-12-13 17:12

    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;
    }
    
    0 讨论(0)
  • 2020-12-13 17:27

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

    const sum = (a: number, b: number) : number => a + b;
    
    0 讨论(0)
提交回复
热议问题