Annotate a numeric function
Difficulty: Easy
Try your first run
No account is needed to try this exercise. Write your answer, run the tests, and use the feedback to improve it.
- Read the examples and the required return value.
- Edit the supplied function in the editor, keeping its name and parameters. Return your answer, then select Run code.
- Use the test feedback to try again. Hints are available without replacing your code.
Implement double(value: number): number to return twice the supplied finite number. Return a numeric value rather than printing it or converting it to text.
What this practices
A TypeScript function signature documents the input and output types. The implementation must also satisfy the arithmetic contract: a function can return the right type while calculating the wrong value.
Work through an example
Input -2.5 produces -5. Doubling preserves the sign of a nonzero input; it does not mean taking an absolute value. Input 0 returns 0, and input 3 returns 6.
Edge cases to check
- Zero is valid input.
- Negative and fractional values are allowed.
- The output must be a number, not a string such as
"6".
TypeScript details
TypeScript's number uses JavaScript numeric behavior, including floating-point arithmetic. A number annotation does not mean integer, and it does not validate external JSON at runtime. This exercise supplies valid numeric inputs; do not add parsing, rounding, or string formatting. The annotation disappears when TypeScript is compiled, while the arithmetic still executes.
Check your reasoning
Explain why a function that always returns zero could pass type checking but fail this exercise. Use both a positive and a negative input to test behavior.
Examples
0036-2.5-5Constraints
Use strict TypeScript and a standalone function. No imports, packages, DOM, network, or file access. Inputs are JSON-compatible with at most 1,000 elements and 100,000 characters. Do not mutate inputs. Return the specified result rather than printing. Medium tasks combine narrowing and typed transformations.
Review lesson: Inference and explicit boundariesA little nudge
Reveal one hint at a time. Give yourself a moment to try it.
- Annotate the parameter and return value as number.
- Arithmetic returns a number without a cast.
Worked solution
Try your own approach first, then compare the reasoning.
function double(value: number): number {
return value * 2;
}
Multiplication by two implements the numeric contract directly. Parameter and return annotations catch incompatible types at compile time, but only behavioral tests distinguish doubling from other numeric operations. No cast, parse, rounding step, or intermediate collection is required.
Complexity
O(1) time and O(1) extra space.
Ready when you are
Write your solution, then run it against the practice tests.
Press Esc, then Tab to leave the editor. Code runs in an isolated browser workspace. Tests support learning, not verified grading.