Identifiers and Keywords in Typescript



In this tutorial, we'll learn about identifiers and keywords in TypeScript. Identifiers and keywords are two fundamental concepts in TypeScript, a statically-typed superset of JavaScript. Identifiers are names we give to variables, functions, classes, and other things in our code. Keywords are special words with specific meanings in TypeScript and can't be used as identifiers.

Identifiers must follow certain rules in naming variables, functions, and classes to avoid syntax errors. On the other hand, using keywords as identifiers can lead to errors and make our code difficult to read and understand.

Rules and Best Practices for Identifiers and Keywords in TypeScript

In TypeScript, Identifiers and Keywords play a critical role in writing maintainable and error-free code.

Identifiers

Here are some rules and best practices to keep in mind when working with Identifiers in TypeScript −

  • Identifiers can only contain letters, digits, underscores (_), and dollar signs ($).

  • Identifiers must begin with a letter, underscore, or a dollar sign ($). They cannot start with a digit

  • Identifiers are case-sensitive. For example, "myVariable" and "myvariable" are two different identifiers.

  • Identifiers should be descriptive and meaningful.

  • Identifiers should not be the same as reserved keywords. This can cause syntax errors in our code. To avoid this, use descriptive names that clearly indicate the purpose of the identifier.

Commonly used identifiers in TypeScript include variables, functions, classes, interfaces, and constants.

Here are some examples of valid identifiers in TypeScript −

const myVariable: string = "Hello world";
let myNumber: number = 42;

On the other hand, here are some invalid identifiers −

let 123invalid: string; // identifier cannot start with a digit
const my-variable: string = "Invalid"; // identifier cannot contain a hyphen
let class: string = "Invalid"; // 'class' is a keyword and cannot be used as an identifier 

Keywords

Here are some rules and best practices to keep in mind when working with Keywords in TypeScript −

  • We should not use reserved keywords as identifiers.

  • Users need to be familiar with the commonly used keywords in TypeScript.

  • If we have to use a reserved keyword in a function or class, we can use a trailing underscore (_) to differentiate it from the keyword. For example, class MyClass_ { }.

Here are some commonly used keywords in TypeScript −

  • let, const, var − Used to declare variables.

  • function − Used to declare a function.

  • class − Used to declare a class.

  • if, else − Used to create conditional statements.

  • for, while, do − Used to create loops.

  • interface − Used to declare an interface.

  • implements − Used to implement an interface.

  • enum − Used to declare an enumeration.

Here’s an example of an invalid Keyword −

let let = "Invalid"; // 'let' is a keyword and cannot be used as an identifier 

Example (Variable Identifier)

In the example below, we have included a variable identifier. The variable languageName stores the name of the language.

// Variable identifier
const languageName: string = "TypeScript";
console.log(`The name of the language is ${languageName}.` ); 

On compiling, it will generate the following JavaScript code −

// Variable identifier
var languageName = "TypeScript";
console.log("The name of the language is ".concat(languageName, ".")); 

Example (Function Identifier)

In the example below, we have included a function identifier. The function greetPerson takes a name parameter and outputs a greeting.

// Function identifier
function greetPerson(name: string): void {
   console.log( `Hello, ${name}!` );
}
greetPerson("Subhman"); 

On compiling, it will generate the following JavaScript code –

// Function identifier
function greetPerson(name) {
   console.log("Hello, ".concat(name, "!"));
}
greetPerson("Subhman"); 

Example (Class Identifier)

In the example below, we have included a class identifier. The class Animal has a name property and a speak method.

// Class identifier
class Animal {
   private name: string;

   constructor(name: string) {
      this.name = name;
   }
   public speak(): void {
      console.log(`${this.name} makes a sound.`);
   }
}

const dog = new Animal("Dog");
dog.speak(); 

On compiling, it will generate the following JavaScript code –

// Class identifier
var Animal = /** @class */ (function () {
   function Animal(name) {
      this.name = name;
   }
   Animal.prototype.speak = function () {
      console.log("".concat(this.name, " makes a sound."));
   };
   return Animal;
}());
var dog = new Animal("Dog");
dog.speak(); 

Example (Interface Identifier)

In the example below, we have included an interface identifier. The interface Shape defines a color property and an area method to return a number. The Rectangle class implements the Shape interface and adds width and height properties and an area method that calculates the area of the rectangle.

// Interface identifier
interface Shape {
   color: string;
   area() : number;
}

class Rectangle implements Shape {
   color: string;
   width: number;
   height: number;

   constructor(color: string, width: number, height: number) {
      this.color = color;
      this.width = width;
      this.height = height;
   }

   area(): number {
      return this.width * this.height;
   }
}
const rect = new Rectangle("red", 5, 10);
console.log(`The area of the ${rect.color} rectangle is ${rect.area()}.`);

On compiling, it will generate the following JavaScript code –

var Rectangle = /** @class */ (function () {
   function Rectangle(color, width, height) {
      this.color = color;
      this.width = width;
      this.height = height;
   }
   Rectangle.prototype.area = function () {
      return this.width * this.height;
   };
   return Rectangle;
}());
var rect = new Rectangle("red", 5, 10);
console.log("The area of the ".concat(rect.color, " rectangle is ").concat(rect.area(), "."));

Example (const, let, if, function & class keywords)

In this example, we use the const, let, if, function, and class keywords in TypeScript. These are all built-in keywords that have a specific meaning and usage within the language.

// TypeScript keyword example

// TypeScript keyword : 'const'
const pi: number = 3.14;

// TypeScript keyword : 'let'
let count: number = 0;

// TypeScript keyword : 'if'
if (count === 0) {
   console.log(" Count is zero ");
}

// TypeScript keyword : 'function'
function multiply(a: number, b: number): number {
   return a * b;
}

// TypeScript keyword : 'class'
class Person {
   private name: string;
   private age: number;
   constructor(name: string, age: number) {
      this.name = name;
      this.age = age;
   }
   public getAge(): number {
      return this.age;
   }
}
const john = new Person("John", 30);
console.log(john.getAge());

On compiling, it will generate the following JavaScript code –

// TypeScript keyword example

// TypeScript keyword : 'const'
var pi = 3.14;

// TypeScript keyword : 'let'
var count = 0;

// TypeScript keyword : 'if'
if (count === 0) {
   console.log(" Count is zero ");
}

// TypeScript keyword : 'function'
function multiply(a, b) {
   return a * b;
}

// TypeScript keyword : 'class'
var Person = /** @class */ (function () {
   function Person(name, age) {
      this.name = name;
      this.age = age;
   }
   Person.prototype.getAge = function () {
      return this.age;
   };
   return Person;
}());
var john = new Person("John", 30);
console.log(john.getAge()); 

In this tutorial, we have explored various aspects of TypeScript identifiers and keywords. We learned that TypeScript has several reserved keywords with predefined meanings and cannot be used as identifiers. We also saw examples of valid and invalid identifiers and keywords and how they can be used in TypeScript code.

The first example demonstrated the usage of variable, function, class, and interface identifiers to define language constructs. The second example showcased the usage of built-in keywords to perform different operations in the language.

Understanding identifiers and keywords is essential when working with TypeScript as it enables us to write more readable and error-free code. By following TypeScript's naming conventions, we can write consistent code that is easier to understand and maintain.


Advertisements