简体   繁体   中英

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?

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

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
  }
}

You can configure your compiler for --noEmitOnError :

Do not emit outputs if any errors were reported.

Though this won't "prevent an execution" per se, it will avoid Typescript's deliberate tendency to allow you to emit even when it detects type errors. From TypeScript development lead RyanCavanaugh in Typescript issue 828 , where that command-line flag was created:

We definitely want the behavior that the compiler can emit in the presence of type errors. This is a key scenario for migrating existing JavaScript -- you rename some.js file to.ts, get some type errors, but want to keep getting compilation of it while you refactor it to remove the type errors. They are 'warnings' in that sense; we cannot guarantee that your program does not work just because it has type errors.

That said, we recognize that this isn't always the behavior you want. Incremental builds get messed up by this on a fairly regular basis. We need something to address this scenario.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM