Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript return type for adhoc return value

Suppose that I have the following function in Typescript 2.0:

doSomething(): any {

    const apple: Apple = ...
    const pears: Pear[] = ...

    return {
        apple: apple,
        pears: pears
    }
}

I know that my function will always return an object that has an apple property of type Apple and a pear property of type Pear[].

I don't especially want to create a new class to model this. Is there anyway to change my return type from any to something more meaningful?

like image 846
sixtyfootersdude Avatar asked Sep 16 '16 14:09

sixtyfootersdude


People also ask

How do I specify a return type of function in TypeScript?

To define the return type for the function, we have to use the ':' symbol just after the parameter of the function and before the body of the function in TypeScript. The function body's return value should match with the function return type; otherwise, we will have a compile-time error in our code.

What does ?: Mean in TypeScript?

Using ?: with undefined as type definition While there are no errors with this interface definition, it is inferred the property value could undefined without explicitly defining the property type as undefined . In case the middleName property doesn't get a value, by default, its value will be undefined .

How do you handle multiple return types in TypeScript?

Use a union type to define a function with multiple return types in TypeScript, e.g. function getValue(num: number): string | number {} . The function must return a value that is represented in the union type, otherwise the type checker throws an error.


1 Answers

You can use an inline interface:

doSomething(): {apple: Apple, pears: Pear[]} {

    const apple: Apple = ...
    const pears: Pear[] = ...

    return {
        apple: apple,
        pears: pears
    }
}
like image 132
toskv Avatar answered Oct 29 '22 18:10

toskv