TypeScript

4.TypeScript Identifiers, Keywords, and Comments – A Complete Guide

🏷 Identifiers in TypeScript

In TypeScript, we use variables, functions, and other entities by giving them specific names. However, naming these entities follows certain rules and conventions. These rules are referred to as identifiers.

📜 Rules for Identifiers:

  • Can contain: Characters (letters), digits (numbers), and underscores (_), or a dollar sign ($).
  • Cannot start with: A digit (e.g., 1number is invalid).
  • Cannot include: Special symbols, except for an underscore (_) or a dollar sign ($).
  • Cannot be a keyword: Reserved words like var, let, class, etc., cannot be used as identifiers.
  • Should not be duplicated: Avoid naming multiple variables or functions with the same name.
  • Are case-sensitive: firstName and FirstName are two different identifiers.
  • Cannot contain spaces: Spaces are not allowed in identifiers.

✅ Example: Valid and Invalid Identifiers

✅ Valid Identifiers ❌ Invalid Identifiers
firstName Var
first_name first name
num1 first-name
$result 1number

🔑 TypeScript Keywords

Keywords are reserved words that have a special meaning in the TypeScript language. These keywords are used to define specific actions or operations and cannot be used as identifiers.

🚨 List of TypeScript Keywords:

  • break, as, any, switch, case
  • if, else, throw
  • var, number, string
  • get, module, type, instanceof
  • typeof, public, private
  • enum, export, finally
  • for, while, void, null
  • super, this, new, in
  • return, true, false, extends
  • static, let, package, implements
  • interface, function, try, yield
  • const, continue, do, catch

💬 Comments in TypeScript

To enhance the readability of your code and make it easier to understand, comments are used. Even if you’re a great coder, it’s common to forget why you wrote a specific piece of code after some time. Well-commented code helps a lot in understanding your logic when revisited later.

✍ Types of Comments in TypeScript:

  1. Single-line Comments
    Use // to write comments on a single line.Example:

    // This is a single-line comment
  2. Multi-line Comments
    Use /* and */ to write comments spanning multiple lines.Example:

    /* This is a  
       Multi-line comment  
    */

Leave a Reply

Your email address will not be published. Required fields are marked *