Skip to main content

Command Palette

Search for a command to run...

TypeScript Casting

Published
•1 min read•View as Markdown

Casting is the process of overriding a type when it's necessary to override the type of a variable, such as when incorrect types are provided by a library.

Casting with as

A straightforward way to cast a variable is using the as keyword, which will directly change the type of the given variable.

Example of using TypeScript Casting in Angular:

@Component({
  selector: 'app-root',
  standalone: true,
  template: `
    <input type="number" [value]="value" (input)="handleInput($event)" />
  `,
})
export class App implements OnInit {
  value!: number;

  ngOnInit(): void {
    this.value = 123;
  }

  handleInput(event: Event) {
    const { value } = event.target as HTMLInputElement; // TypeScript Casting to tell TypeScript that this is in fact an HTML input element
    console.log(value);
  }
}

Casting doesn't actually change the type of the data within the variable, for example the following code will not work as expected since the variable x is still holds a number.

let x: unknown = 4;
console.log((x as string).length); // prints undefined since numbers don't have a length