We use cookies to enhance your experience on the site
CodeWorlds

TypeScript for Angular - The Bushido Code of Code

TypeScript is the language that Angular requires to work. It is like the Bushido code - it imposes discipline, but in return provides reliability and predictability.

Why TypeScript?

TypeScript is JavaScript with static typing:

  • Catches errors before running the code
  • Better autocompletion in the editor
  • Self-documenting code
  • Refactoring without fear

Basic Types

1// Simple types
2const name: string = 'Musashi';
3const age: number = 25;
4const isActive: boolean = true;
5
6// Arrays
7const techniques: string[] = ['Kendo', 'Iaido', 'Judo'];
8const levels: Array<number> = [1, 2, 3, 4, 5];
9
10// Objects with interface
11interface Samurai {
12  name: string;
13  clan: string;
14  level: number;
15  techniques?: string[]; // ? means optional
16}
17
18const warrior: Samurai = {
19  name: 'Miyamoto Musashi',
20  clan: 'Niten Ichi-ryū',
21  level: 10
22};

Types in Angular

Typing components

1import { Component, Input, Output, EventEmitter } from '@angular/core';
2
3interface Task {
4  id: number;
5  name: string;
6  completed: boolean;
7}
8
9@Component({
10  selector: 'app-task-list',
11  standalone: true,
12  template: \`
13    @for (task of tasks; track task.id) {
14      <div (click)="select(task)">
15        {{ task.name }}
16      </div>
17    }
18  \`
19})
20export class TaskListComponent {
21  @Input() tasks: Task[] = [];
22  @Output() taskSelected = new EventEmitter<Task>();
23
24  select(task: Task): void {
25    this.taskSelected.emit(task);
26  }
27}

Typing services

1import { Injectable } from '@angular/core';
2import { Observable, of } from 'rxjs';
3
4interface Samurai {
5  id: number;
6  name: string;
7  rank: string;
8}
9
10@Injectable({
11  providedIn: 'root'
12})
13export class SamuraiService {
14  private samuraiList: Samurai[] = [
15    { id: 1, name: 'Musashi', rank: 'Master' },
16    { id: 2, name: 'Kojiro', rank: 'Expert' }
17  ];
18
19  getSamuraiList(): Observable<Samurai[]> {
20    return of(this.samuraiList);
21  }
22
23  getSamuraiById(id: number): Observable<Samurai | undefined> {
24    return of(this.samuraiList.find(s => s.id === id));
25  }
26}

Strict Mode - The Highest Level of Discipline

In `tsconfig.json`, Angular enables strict mode by default:

1{
2  "compilerOptions": {
3    "strict": true,
4    "noImplicitAny": true,
5    "strictNullChecks": true,
6    "strictPropertyInitialization": true
7  }
8}

It is like training under the strictest master - demanding, but shaping the best code warriors!

Go to CodeWorlds