How to make Typescript throw runtime error?

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
 constructor() {
   console.log(this.getColor(1000))
}
getColor(c:String) {
  return c
}
}

My text editor put a red line bellow the 1000 that's says: Argument of type '1000' is not assignable to parameter of type 'String'.ts(2345)

Ok...but my app still executes and I can have the result on my console.

is there any how to make Angular and/or Typescript to prevent an execution in a scenario like this ?


Solution 1:

Typescript is only warning you, that something is not right. It does still compile and you can still run the code and it can work, but it is not intended to work like that.

So how can you check if the input is correct?

function example (color: string): void {
  if (typeof color !== 'string') {
    throw Error() // you can put your error message in here
  }
}

UPDATE 15.01.2022

I'd suggest changing my above solution a tad. With new typescript features, you could write

interface IColor extends string

function isColor(color: any): color is IColor {
  if (typeof color !== 'string') return false
  return true
}

function example (input: string): void {
  if (isColor(input)) {
    throw Error() // you can put your error message in here
  }
  // everything you wanna do here
}

Some advantages over my old suggestion:

  • IColor is changeable or extensible to numbers or hexadecimals
  • isColor can be used anywhere to check if sth is a valid color

Solution 2:

Your browser does not know about TypeScript, it only executes the transpiled javascript code.

But in your situation, the build process (made by Angular) will raise errors and you won't be able to deploy your application.

In dev mode a typescript error is raised but you still can execute the application for practical reasons