打字稿 - 空检查后,对象可能是“空”.ts(2531)

时间:2021-05-20 10:21:43

标签: typescript syntax-error

空检查后,我得到 Object 可能是 'null'.ts(2531)。有人可以帮我吗?我做错了什么吗?

    let array_of_some_data: ({ some_value: number } | null)[] = [];

    //Getting Object is possible 'null' error as expected. Because I didn't check null before trying to access value.
    array_of_some_data[0].some_value = 5;

    //Not getting error as expected since I've checked null this time.
    if (array_of_some_data[0] !== null) array_of_some_data[0].some_value = 5;
    
    //Why am I getting Object is possible 'null' error here? Only difference from above line is I've stored index value in a const.
    const x: number = 0;
    if (array_of_some_data[x] !== null) array_of_some_data[x].some_value = 5;

0 个答案:

没有答案