My function looks like this:
parseRange = (text) => { var arr = []; var lower = null; var upper = null; if (!text || text === "") { lower = null; upper = null; } else if (text.indexOf("-") > 0) { arr = text.split("-"); lower = +arr[0]; upper = +arr[1]; } else { lower = +text; upper = null; } return { lower: lower, upper: upper }; };
I am familiar with returning strings and numbers but how can I specify the return is an object with a lower and upper parameter?
The function's return type is string. Line function returns a string value to the caller. This is achieved by the return statement. The function greet() returns a string, which is stored in the variable msg.
Inside the function we assign the parameters to properties in the object. To do this, we have to specify the this keyword, which refers to the calling object. The variables and parameters may have the same names. Anything we pass to the constructor as an argument, will be assigned to the property of the object.
A function can also return objects either by value or by reference. When an object is returned by value from a function, a temporary object is created within the function, which holds the return value. This value is further assigned to another object in the calling function.
parseRange = (text: string) : { lower: number; upper: number; } => { // ... return { lower: lower, upper: upper }; };
or
parseRange = <(text: string) : { lower: number; upper: number; }> ((text) => { // ... return { lower: lower, upper: upper }; });
or
var parseRange : (text: string) => { lower: number; upper: number; } = (text) => { // ... return { lower: lower, upper: upper }; };
or
parseRange = function (text: string) : { lower: number; upper: number; } { // ... return { lower: lower, upper: upper }; };
or
function parseRange(text: string) : { lower: number; upper: number; } { // ... return { lower: lower, upper: upper }; };
or
interface RangeResult { lower: number; upper: number; } function parseRange(text: string) : RangeResult { // ... return { lower: lower, upper: upper }; };
TypeScript infers function return types, so this results in a compile error without having to specify the types explicitly:
var parseRange = (text) => { return { lower: 5, upper: 6 }; }; var range = parseRange(""); range.foo; // compile error
Live example which shows the error:
The property 'foo' does not exist on value of type '{ lower: number; upper: number; }'.
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