微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

[Typescript] Type Guard: is & assert

value is Foo

The first kind of user-defined type guard we will review is an is type guard. It is perfectly suited for our example above because it’s meant to work in cooperation with a control flow statement of some sort, to indicate that different branches of the “flow” will be taken based on an evaluation of valuetoTest’s type. Pay very close attention to isCarLike’s return type

interface CarLike {
  make: string
  model: string
  year: number
}
 
let maybeCar: unkNown
 
// the guard
function isCarLike(
  valuetoTest: any // should be flexable
): valuetoTest is CarLike {
  return (
    valuetoTest &&
    typeof valuetoTest === "object" &&
    "make" in valuetoTest &&
    typeof valuetoTest["make"] === "string" &&
    "model" in valuetoTest &&
    typeof valuetoTest["model"] === "string" &&
    "year" in valuetoTest &&
    typeof valuetoTest["year"] === "number"
  )
}
 
// using the guard
if (isCarLike(maybeCar)) {
  maybeCar // CarLike
}

 

asserts value is Foo

There is another approach we Could take that eliminates the need for a conditional. Pay very close attention to assertsIsCarLike’s return type:

interface CarLike {
  make: string
  model: string
  year: number
}
 
let maybeCar: unkNown
 
// the guard
function assertsIsCarLike(
  valuetoTest: any
): asserts valuetoTest is CarLike {
  if (
    !(
      valuetoTest &&
      typeof valuetoTest === "object" &&
      "make" in valuetoTest &&
      typeof valuetoTest["make"] === "string" &&
      "model" in valuetoTest &&
      typeof valuetoTest["model"] === "string" &&
      "year" in valuetoTest &&
      typeof valuetoTest["year"] === "number"
    )
  )
    throw new Error(
      `Value does not appear to be a CarLike${valuetoTest}`
    )
}

maybeCar // unkNown
assertsIsCarLike(maybeCar)
maybeCar // CarLike

 

Conceptually, what’s going on behind the scenes is very similar. By using this special Syntax to describe the return type, we are informing TypeScript that if assertsIsCarLike throws an error, it should be taken as an indication that the valuetoTest is NOT type-equivalent to CarLike.

Therefore, if we get past the assertion and keep executing code on the next line, the type changes from unkNown to CarLike.

 

Writing high-quality guards

Type guards can be thought of as part of the “glue” that connects compile-time type-checking with the execution of your program at runtime. It’s of great importance that these are designed well, as TypeScript will take you at your word when you make a claim about what the return value (or throw/no-throw behavior) indicates.

Let’s look at a bad example of a type guard:

function isNull(val: any): val is null {
  return !val
}
 
const empty = ""
const zero = 0
if (isNull(zero)) {
  console.log(zero) // is it really impossible to get here?
}
function isNull(val: any): val is null {
  return !val
}
 
const empty = ""
const zero = 0
if (isNull(zero)) {
  console.log(zero) // is it really impossible to get here?
               
const zero: never
}
if (isNull(empty)) {
  console.log(empty) // is it really impossible to get here?
}

 

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐