Hacker News new | ask | show | jobs
by skn0tt 2498 days ago
When it comes to API responses you don't control, I recommend taking a look at user-defined type guards: https://basarat.gitbooks.io/typescript/content/docs/types/ty...

Also, +1 on tslint and prettier, they're great tools.

1 comments

> type guard

Thanks for the link, I am currently doing something similar without knowing TS implicit behavior.

With 1st given example in the link, I forced on a style to such:

```

function doSomething(x: number | string) { if (typeof x === 'string') { doSomethingForString(x) }

  // Never do catch all to assume all non-strings are numbers
  if (typeof x === 'number') {
    doSomethingForNumber(x)
  }

  // Per transpiler rule, you not meant to be here, so error throwing is appropriate
  throw new Error('Unexpected type')
}

function doSomethingForString(x: string) { // Code }

function doSomethingForNumber(x: number) { // Code }

```