ameena
ameena

Reputation: 23

How can I throw a type error in Typescript

I’m stuck with the following Typescript problem:

Write a function that decides whether a user is logged in. Sometimes, it's called with a number of times that the user is logged in. Other times, it's called with true. It's never called with false

My code so far:

function isLoggedIn(param: number | boolean ) {
  if (param === 0) {
    return false
  } else if (param === false) {   
    return false
  } else {
    return true
  }
}

I can’t figure out how to handle the case when the function is called with false, so that a type error could be returned. If I do: if (param === false) {return false} , I get back an error

Expected: type error but got: false

If I throw the TypeError myself, i.e. if (arg === false) throw new TypeError('type error') I get back an error "Expected: type error but got: TypeError: 'type error'

Does anyone know how to make the function work?

Upvotes: 2

Views: 3053

Answers (1)

leonardfactory
leonardfactory

Reputation: 3501

I suppose that the Type error referred in the question, is not a JS TypeError but a TypeScript type error at compile time, so something like:

Argument of type 'false' is not assignable to parameter of type 'number | true'.(2345)

You can change your declaration to be:

function isLoggedIn(param: number | true) {
  if (param === 0) {
    return false
  } else {
    return true
  }
}

See number | true. Here true is meant to represent the literal "true" value, not just a boolean, so that you can pass "true" but not "false".

You should adapt the if condition inside too, since param will never be false, as posted in the example. So you can use it like:

isLoggedIn(10); // ok
isLoggedIn(true); // ok
isLoggedIn(false); // TS Error

You can check it here: Playground Link

Upvotes: 2

Related Questions