【问题标题】:Why does this typescript typeguard not work为什么这个打字稿类型保护不起作用
【发布时间】:2021-03-11 04:05:39
【问题描述】:

我有以下代码

const validProtocols = ["https", "http"] as const
type AllProtocols = typeof validProtocols
type Protocol = AllProtocols[number]
function isProtocol(p:unknown): p is Protocol{
  return typeof p === "string" && p in validProtocols
}

let parse = (p:string)=>{
  if(isProtocol(p))
    return p
  else
    throw `${p} is not a protocol`
}

console.log(parse("https"))

代码编译,但最后一行抛出 isProtocol(p) 返回 false。怎么了?

代码将用于验证编译器无法控制的输入,即:环境变量。

【问题讨论】:

    标签: typescript typeguards


    【解决方案1】:

    in 运算符检查对象上是否存在 属性。例如:

    const obj = { prop: 'val' };
    const arr = ['val'];
    
    console.log('prop' in obj, 0 in arr);

    它不检查值,只检查属性。要检查数组中的值,请使用 .includes(您还必须解决 ugly type rules for .includes 问题,这会使此类检查比预期的要复杂得多):

    function isProtocol(p:unknown): p is Protocol{
      return typeof p === "string" && (validProtocols as unknown as Array<string>).includes(p)
    }
    

    【讨论】:

    • 为什么要进行类型转换? validProtocols 是不是字符串数组?
    • 它比这更具体 - 它的类型为 ["https", "http"],不幸的是,TypeScript 不允许使用数组中可能不存在的元素调用 .includes。许多人不同意设计决策,所以现在,要执行这样的检查,你需要一个解决方法,比如答案中的丑陋类型断言。
    • 好的,这里是as const 更多信息。 blog.logrocket.com/… 感谢您的信息。
    猜你喜欢
    • 1970-01-01
    • 2018-06-08
    • 2021-03-25
    • 1970-01-01
    • 2017-05-18
    • 2020-07-27
    • 2020-08-01
    • 2015-01-12
    • 1970-01-01
    相关资源
    最近更新 更多