Introduction
In this chapter, we will explore the basic syntax of TypeScript by examining a simple TypeScript program. Understanding the basic syntax is crucial for writing TypeScript code effectively.
Table of Contents
- Basic TypeScript Syntax
- Declaring Variables
- Functions
- Type Annotations
- Conclusion
Basic TypeScript Syntax
Let's revisit the simple TypeScript program we wrote in the previous chapter and break down its syntax:
// src/index.ts
function greet(name: string): string {
return `Hello, ${name}! Welcome to TypeScript.`;
}
const userName = "Ravi";
console.log(greet(userName));
Declaring Variables
In TypeScript, you can declare variables using let
, const
, or var
. However, let
and const
are preferred due to their block-scoping behavior.
let
: Used to declare a variable whose value can be changed.const
: Used to declare a constant whose value cannot be changed.
Example
let age: number = 30; // The value of 'age' can be changed
const name: string = "Ravi"; // The value of 'name' cannot be changed
Functions
Functions in TypeScript are similar to those in JavaScript, but with added type annotations for parameters and return types.
Example
function greet(name: string): string {
return `Hello, ${name}! Welcome to TypeScript.`;
}
Explanation:
function
: Keyword to declare a function.greet
: Name of the function.name: string
: Parametername
with type annotationstring
.: string
: Return type annotation, indicating that the function returns a string.`Hello, ${name}! Welcome to TypeScript.`
: Template string used to return a greeting message.
Type Annotations
Type annotations are used to specify the types of variables, parameters, and return values. They help in catching type-related errors during development.
Example
const userName: string = "Ravi";
let age: number = 30;
Explanation:
userName: string
: VariableuserName
is annotated with the typestring
.age: number
: Variableage
is annotated with the typenumber
.
TypeScript uses type annotations to explicitly specify types for identifiers such as variables, functions, objects, etc.
TypeScript uses the syntax : type
after an identifier as the type annotation, which type can be any valid type.
Console Output
The console.log
method is used to print messages to the console. It is useful for debugging and displaying output.
Example
console.log(greet(userName));
Explanation:
console.log
: Method to print messages to the console.greet(userName)
: Calls thegreet
function withuserName
as the argument and prints the returned message.
Conclusion
In this chapter, we explored the basic syntax of TypeScript by breaking down a simple program. We learned how to declare variables, define functions, use type annotations, and print output to the console. Understanding these basics is essential for writing effective TypeScript code.
Comments
Post a Comment
Leave Comment