Home > Enterprise >  Does this code snippet work by lying to Typescript?
Does this code snippet work by lying to Typescript?

Time:12-12

I was reading the official Typescript documentation and came across this example in the type predicate section:

function isFish(pet: Fish | Bird): pet is Fish {
  return (pet as Fish).swim !== undefined;
}

I think I understand type predicates, but don't understand the pet as Fish1 part. In this code snippet, isn't the programmer lying to typescript just to get the predicate to work? It seems to me the isFish function that returns the predicate is telling typescript "this is a Fish" so that it won't throw a TypeError because the so-called Fish isn't guaranteed to have a swim method. Is this understanding correct :)

CodePudding user response:

its true, that this isnt really a clean solution, i suppose this is done to differentiate the example from the in operator mentioned earlier. Also it might be to illustrate that you can do whatever you want to assert that the object is question is of a particular type, because thats the whole purpose of type predicates.

a cleaner implementation of this function would indeed use the in operator instead of a type assertion imo:

function isFish(pet: Fish | Bird): pet is Fish {
  if ('swim' in pet)
     // possibly do more stuff to check its really a Fish, pet is already narrowed to type Fish in this case
    return true
  else 
    return false
}

edit:

also the type assersion allows you to freely do stuff with the pet in question, writing everything typesafe using ins for exampe can be a bit cumbersome if you work with complex types, especially when the whole purpose is to assert it is in fact some given type

  • Related