Mastering TypeScript by Applying These Rules
Emma Richardson
Posted on October 17, 2024
Identifiers:
Identifiers are names assigned to elements like variables, methods, classes, arrays, etc., within a TypeScript program. There are specific rules that must be followed when declaring identifiers:
Identifier Naming:
An identifier can start with either an uppercase or lowercase letter: myVariable, MyClass
It cannot begin with a number:
2variable is invalid.Only two symbols, _ (underscore) and $ (dollar sign), are allowed within an identifier:
_myVariable, my$Method are valid.Identifiers cannot contain spaces or other special characters:
my-variable, my#var are invalid.
Case Sensitivity:
Identifiers are case-sensitive, meaning myVariable and MyVariable are considered two distinct identifiers.
No Reserved Keywords:
Identifiers cannot use reserved TypeScript keywords, such as if, else, class, etc., as names.
Examples of Valid and Invalid Identifiers:
• Valid: myVariable, _temp, my$Method, Array1
• Invalid: 2ndValue, my-variable, class, #temp
2. Keywords:
Keywords in TypeScript are predefined words that perform specific actions or represent certain functionalities. These cannot be used as identifiers (variable names, function names, etc.). Some common TypeScript keywords include:
• Control Flow: if, else, switch, case, break
• Data Types: any, number, string, boolean, void
• Class Modifiers: public, private, protected, readonly
• Other: as, get, set, typeof, instanceof, module, type
3. Variable Declaration:
Variables can be declared using let, const, or var (though var is generally discouraged due to scoping issues).
let age: number = 25;
const name: string = "Alice";
4. Type Annotations:
TypeScript supports static typing, where you can annotate variables, function parameters, and return values with types.
let isValid: boolean = true;
function add(a: number, b: number): number {
return a + b;
}
5. Interfaces and classes:
TypeScript allows the definition of interfaces and classes, promoting object-oriented programming.
interface Person {
name: string;
age: number;
}
class Employee implements Person {
constructor(public name: string, public age: number) {}
}
6. Modules and Imports:
TypeScript supports modular code with import and export statements.
import { Employee } from './Employee';
export class Manager extends Employee {}
If you're interested in learning TypeScript, check out my Medium publication for a TypeScript step-by-step tutorial: https://medium.com/@CodingAdventureWithEmma
Posted on October 17, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.