As you are struggling with both the syntax and meaning, I will provide a thorough explanation.
roundToTwo
is categorized as a function type, not a number
Based on this definition:
const roundToTwo = (num: number) => {
return +(Math.round(+(num + "e+2")) + "e-2")
}
this is the actual (and correctly inferred) type of roundToTwo
:
(num: number) => number
Why? Because roundToTwo
represents a function type, not a number. The type is deduced from the function expression being assigned to it. Remember, functions in Javascript are considered first-class objects which extends to Typescript where they are regarded as first-class types.
However, declaring const roundToTwo: number
gives it the type number
This is what you erroneously did initially in your new declaration. You stated, "roundToTwo is a number," and subsequently attempted to assign a function to it, resulting in an expected type error:
const roundToTwo: number = (num: number) => {
return +(Math.round(+(num + "e+2")) + "e-2")
}
// compare the above to:
const roundToTwo: number = 2
const n: number = 2
Explicitly typing it is unnecessary
There's no need to explicitly specify the type for roundToTwo
since you immediately assigned it a function expression, and the inferred type aligns with your intention. Just like how you don't have to include : number
in this assignment:
const max = 42 // equivalent to "const max: number = 42"
If you only desired to specifically define the return value of the function expression
Add the :number
after the parameter signature like so:
const roundToTwo = (num: number):number => {
return +(Math.round(+(num + "e+2")) + "e-2")
}
If your intention was to explicitly determine the roundToTwo
variable
You have two options.
The inline syntax:
const roundToTwo: (num: number) => number = (num: number) => {
return +(Math.round(+(num + "e+2")) + "e-2")
}
Utilizing a type alias:
type numericFunction = (num: number) => number
const roundToTwo: numericFunction = (num: number) => {
return +(Math.round(+(num + "e+2")) + "e-2")
}
The type alias enhances readability particularly for more intricate function signatures, but more importantly, it proves beneficial when referencing this function type elsewhere, such as within a function parameter:
function scaleArray(arr: number[], scaleFunc: numericFunction): number {
}