Code Logo

Basic Type Annotations

Published at24 Jul 2026
TypeScript Functions Easy 0 views
Like0

Write a TypeScript function that demonstrates type annotations. The function takes a name (string) and age (number) and returns a formatted greeting string with the type signature : string.

TypeScript type annotations use colon syntax: param: type for parameters and ): type for return values. This function explicitly declares both parameter types and the return type.

This is a foundational TypeScript concept. Unlike plain JavaScript, TypeScript catches type mismatches at compile time, preventing runtime errors.

TypeScript type annotations are a core language feature that enables compile-time type checking. Annotating function parameters and return values documents the expected types and catches errors during development rather than at runtime.

The colon syntax param: type for parameters and ): returnType for return values is consistent throughout TypeScript. TypeScript's type inference can often deduce types without explicit annotations, but explicit annotations improve code readability and enforce contracts.

TypeScript type annotations are a core language feature enabling compile-time type checking. Annotating function parameters and return values documents expected types and catches errors during development rather than at runtime. TypeScript's type inference often deduces types automatically, but explicit annotations improve code readability.

Example Input & Output

Example 1
Input
"Bob", 25
Output
"Bob is 25 years old"
Example 2
Input
"Alice", 30
Output
"Alice is 30 years old"
Example 3
Input
"Diana", 22
Output
"Diana is 22 years old"
Example 4
Input
"Charlie", 40
Output
"Charlie is 40 years old"
Example 5
Input
"Eve", 35
Output
"Eve is 35 years old"

Algorithm Flow

Recommendation Algorithm Flow for Basic Type Annotations
Recommendation Algorithm Flow for Basic Type Annotations

Solution Approach

Define the function with typed parameters: name: string, age: number. Use string concatenation or template literals to build the result. Return a string with the format 'Name is AGE years old'.

The return type annotation : string after the parameter list declares what type the function returns.

Best Answers

typescript - Approach 1
function greet(name: string, age: number): string {
    return name + ' is ' + age + ' years old';
}