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?
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.
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 .
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.
You can use an inline interface:
doSomething(): {apple: Apple, pears: Pear[]} {
const apple: Apple = ...
const pears: Pear[] = ...
return {
apple: apple,
pears: pears
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With