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

 

posted @   Zhentiw  阅读(47)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2021-08-03 [SAA + SAP] 17. RDS - Aurora
2018-08-03 [JavaEE] Injecting Bean
2017-08-03 [D3] Start Visualizing Data Driven Documents with D3 v4
2017-08-03 [Angular] Setup automated deployment with Angular, Travis and Firebase
2017-08-03 [Angular] Intercept HTTP requests in Angular
2016-08-03 [React Native] Using the WebView component
点击右上角即可分享
微信分享提示