gpt4 book ai didi

typescript - 狭窄的未知对象

转载 作者:行者123 更新时间:2023-12-03 23:02:34 25 4
gpt4 key购买 nike

我有一个接受用户输入的函数,参数类型是 unknown .我想断言...

  • value是一个对象
  • value有一个名为 "a" 的 key

  • function x(value: unknown){
    if(value === null || typeof value !== 'object'){
    throw new Error('Expected an object');
    }

    if(!('a' in value)){
    throw new Error('Expected an object to contain property "a"');
    }
    }
    typescript 提示“对象可能是‘空’”……
    Object is possibly null
    如何缩小范围 unknown到一个对象?

    最佳答案

    有趣的是,你只需要切换支票的顺序:( playground )

    function x(value: unknown){
    if(typeof value !== 'object' || value === null){
    // ^^^^ check type and then check null ^^
    throw new Error('Expected an object');
    }

    if(!('a' in value)){
    throw new Error('Expected an object to contain property "a"');
    }
    }
    这是因为检查 unknown 不为 null 不能真正缩小范围,但在 typeof value !== 'object' 之后它将可能的类型限制为 objectnull因此,针对该类型检查 null 大小写确实会按照您想要的方式缩小范围。

    关于typescript - 狭窄的未知对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64683427/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com