Understanding the role of Identifiers & Keywords in Typescript

img
offshore engineering specialist at Code B - Shagun Deogharkar
Shagun Deogharkar Software Engineer @ Code-Bauthor linkedin
Published On
Updated On
Table of Content
up_arrow

What is typescript?

Understanding the role of Identifiers & Keywords in Typescript

TypeScript, an extension of JavaScript, brings a robust type system to web development, making it easier to write maintainable and scalable code. Two fundamental aspects of TypeScript—and indeed any programming language—are identifiers and keywords. Understanding their roles and proper usage is crucial for harnessing the full power of TypeScript.

What are Identifiers?

Identifiers in TypeScript are names given to various program elements, such as variables, functions, classes, and interfaces. They reference these elements, allowing programmers to interact with them throughout their code. Identifiers must adhere to specific naming rules to ensure clarity and avoid conflicts.

what are identifiers

Naming Rules for Identifiers

To maintain clarity and avoid conflicts in TypeScript, identifiers must adhere to specific naming rules:

  • Character Set: Identifiers can consist of letters (both uppercase and lowercase), digits (0-9), underscores (_), and dollar signs ($). However, they cannot start with a digit.

  • Case Sensitivity: Identifiers are case-sensitive, meaning that myVariable, MyVariable, and MYVARIABLE are considered different identifiers.

  • Reserved Keywords: Identifiers cannot be the same as reserved keywords in TypeScript, such as if, else, for, class, etc.

  • Length: While there is no strict limit on the length of identifiers, it is advisable to keep them reasonably short and descriptive for better readability.

Best Practices for Using Identifiers

To enhance code readability and maintainability, consider the following best practices when naming identifiers:

  • Descriptive Names: Use meaningful names that convey the purpose of the variable or function. For example, instead of using x, use totalPrice for a variable that holds the total price of items.

  • Camel Case: For variables and functions, use camelCase (e.g., calculateTotal) to improve readability. For class names, use PascalCase (e.g., ShoppingCart).

  • Avoid Abbreviations: Unless widely recognized, avoid using abbreviations that may confuse readers. For instance, prefer customerAddress over custAddr.

  • Consistency: Use consistent naming conventions throughout your codebase to help others (and yourself) understand the code.

Identifiers Examples

Here are a few examples of identifiers in TypeScript, along with their outputs:

Variable Declaration

let userName: string = "Shagun D";
console.log(userName);

// Output
Shagun D

Function Declaration

function greetUser(name: string): string {
return `Hello, ${name}!`;
}

console.log(greetUser("Shagun"));

// Output
Hello, Shagun!

Class Declaration

class Club {
name: string;
slogan: string;
founded: number;

constructor(name: string, slogan: string, founded: number) {
this.name = name;
this.slogan = slogan;
this.founded = founded;
}

getCarInfo(): string {
return `${this.founded} ${this.name} ${this.slogan}`;
}
}

const myClub = new Club("Real Madrid", "hala madrid y nada mas", 1902);
console.log(myClub.getCarInfo());


// Output
1902 Real Madrid hala madrid y nada mas

Interface Declaration

interface Person {
firstName: string;
lastName: string;
age: number;
}

const person: Person = {
firstName: "Shagun",
lastName: "D",
age: 25
};

console.log(`${person.firstName} ${person.lastName}, Age: ${person.age}`);

// Output
Shagun D, Age: 25

Enum Declaration

enum Direction {
North,
South,
East,
West
}

let currentDirection: Direction = Direction.North;
console.log(currentDirection); // Enum value
console.log(Direction[currentDirection]); // Enum name

// Output
0
North

Type Alias Declaration

type Point = {
x: number;
y: number;
};

const point: Point = {
x: 10,
y: 20
};

console.log(`Point coordinates: (${point.x}, ${point.y})`);

// Output
Point coordinates: (10, 20)

What are Keywords?

Keywords are reserved words in TypeScript that have special meanings and cannot be used as identifiers. They are integral to the language's syntax and structure, guiding the interpreter on how to parse and execute the code. Keywords are predefined and serve specific functions in the language.

What are keywords

Common TypeScript Keywords

  1. Control Flow: if, else, switch, case, for, while, do, break, continue

  2. Declarations: var, let, const, function, class, interface, enum, type

  3. Types: number, string, boolean, void, any, never, unknown

  4. Access Control: public, private, protected, readonly

  5. Others: import, export, extends, implements, new, super, this, static, abstract, as, async, await

Using Keywords Effectively

  1. Control Flow: Keywords like if, else, and switch are used to create conditional statements, while for, while, and do help in creating loops. Proper use of these keywords can make the code more efficient and readable.

  2. Variable Declarations: var, let, and const are used to declare variables, with let and const being block-scoped and var being function-scoped. Understanding the differences and choosing the right keyword for variable declaration is vital for avoiding scope-related issues.

  3. Type Declarations: Keywords like number, string, and boolean are used to declare the types of variables, ensuring type safety. Using these keywords helps in catching type-related errors during development, leading to more robust code.

  4. Access Control: public, private, and protected control the visibility of class members. readonly ensures that a property can only be assigned during initialization or in the constructor, enhancing the security and integrity of the class.

  5. Modules and Imports: import and export are used for modular programming, allowing developers to split their code into reusable modules. This leads to better organization and maintainability of the codebase.

  6. Asynchronous Programming: async and await facilitate asynchronous programming, making it easier to work with promises and asynchronous functions.

Keywords Examples

Here are a few examples of identifiers in Keywords, along with their outputs:

Control Flow

function checkAge(age: number): string {
if (age < 18) {
return "Minor";
} else if (age < 65) {
return "Adult";
} else {
return "Senior";
}
}

console.log(checkAge(25))

// Output
Adult

Variable Declaration

let userName: string = "John Doe";
const userAge: number = 30;

Type Declaration

function add(a: number, b: number): number {
return a + b;
}

Access Control

class Person {
private name: string;
protected age: number;
public readonly id: number;

constructor(name: string, age: number, id: number) {
this.name = name;
this.age = age;
this.id = id;
}

public getName(): string {
return this.name;
}
}

Modules and Imports

// math.ts
export function add(a: number, b: number): number {
return a + b;
}

// app.ts
import { add } from './math';

console.log(add(2, 3));

// Output
5

Asynchronous Programming

async function fetchData(url: string): Promise<any> {
const response = await fetch(url);
return response.json();
}

fetchData('https://api.example.com/data')
.then(data => console.log(data))
.catch(error => console.error(error));

Conclusion

Understanding the role of identifiers and keywords in TypeScript is fundamental to writing clean, efficient, and maintainable code. Identifiers provide a way to name and reference various elements in your code, while keywords form the backbone of the language’s syntax and structure. By following best practices for naming identifiers and effectively using keywords, developers can leverage TypeScript to its full potential, resulting in more robust and error-free applications.

Staying current with TypeScript’s evolving features and incorporating them into your projects ensures that you remain at the forefront of modern web development. Whether you're declaring variables, creating classes, or managing control flow, a deep comprehension of these core concepts will significantly enhance your coding experience. Happy coding!

Schedule a call now
Start your offshore web & mobile app team with a free consultation from our solutions engineer.

We respect your privacy, and be assured that your data will not be shared