GV000
GV000
  • 发布:2023-12-01 18:43
  • 更新:2023-12-01 20:46
  • 阅读:458

JSON.parse<UTSJSONObject>(systemInfo) 类型错误?

分类:uts
function getStatusBarHeight():UTSJSONObject {  
    let parseRes: UTSJSONObject = {}  
    const systemInfo:string = uni.getStorageSync("systemInfo")  
    if(systemInfo && systemInfo !== null){  
        parseRes = JSON.parse<UTSJSONObject>(systemInfo)  
    }  
    return parseRes  
}
2023-12-01 18:43 负责人:无 分享
已邀请:
GV000

GV000 (作者) - 全栈开发工程师

error: Type mismatch: inferred type is UTSJSONObject? but UTSJSONObject was expected‌

这是报错内容

parseRes = JSON.parse<UTSJSONObject>(systemInfo)
这是报错代码

YUANRJ

YUANRJ

JSON.parse可能会返回null,需要加非空断言。

function getStatusBarHeight():UTSJSONObject {    
    let parseRes: UTSJSONObject = {}    
    const systemInfo:string = uni.getStorageSync("systemInfo")  as string  
    if(systemInfo !== null){    
        parseRes = JSON.parse<UTSJSONObject>(systemInfo)!  
    }    
    return parseRes    
}
  • GV000 (作者)

    加了,报错如下

    ‌error: Type mismatch: inferred type is String but Boolean was expected‌


    报错代码

    if(systemInfo && systemInfo !== null){

    2023-12-01 20:35

  • YUANRJ

    回复 e***@163.com: 已更新回复,最好做下类型判断

    2023-12-01 20:50

  • GV000 (作者)

    回复 YUANRJ:


    function getStatusBarHeight():UTSJSONObject {

    let parseRes: UTSJSONObject = {}

    const systemInfo:string = uni.getStorageSync("systemInfo") as string

    if(systemInfo !== ""){

    parseRes = JSON.parse<UTSJSONObject>(systemInfo)!

    }

    // parseRes = JSON.parse<UTSJSONObject>(systemInfo)!

    return parseRes

    }


    你那个写法会有警告,这样好像就没有问题了

    2023-12-01 20:52

要回复问题请先登录注册