sixtyfootersdude sixtyfootersdude - 2 months ago 11
TypeScript Question

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?

Answer

You can use an inline interface:

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

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

    return {
        apple: apple,
        pears: pears
    }
}