如何描述打字稿中的| undefined?

时间:2020-07-21 03:00:29

标签: typescript

const localAuth = async (callback: () => any) => { 
// not sure the return type of callback, so cast a any type
  const ok = Math.random()
  if (ok > 0.5)
    return callback()
  else {
    return null
}}

localAuth(() => null).then(val => { 
  console.log(val.mayNotExist) // doesn't complain, but val maybe null!
})

打字稿代码如上,因为不确定回调的返回类型,所以我给它分配了任何类型,但显然任何类型都吞噬了“空路径”,如何更改代码以免错过空值的可能性?

1 个答案:

答案 0 :(得分:3)

将您的localAuth函数的返回类型明确定义为回调类型和null的并集。

type anyFunction = () => any;

const localAuth = async (callback: anyFunction): Promise<null|anyFunction> => {
    const ok = Math.random()
    if (ok > 0.5)
        return callback()
    else {
        return null;
    }
};

localAuth(() => null).then(val => {

    console.log(val.arguments) // complains because val may be null

    if (val) {
        console.log(val.arguments) // doesn't complain, because you've checked
    }
    
});

这样,您就可以按预期从Object is possibly 'null'示例的打字稿编译器中收到val.mayNotExist问题。

Typescript playground link,以便您可以看到它的运行情况

编辑1:

要回答您的评论,您可以使用类型别名。

const localAuth = async <T>(callback: () => T): Promise<null | T> => {
    const ok = Math.random()
    if (ok > 0.5)
        return callback()
    else {
        return null;
    }
};

localAuth(() => null).then(val => {

    // val is type null
    
});

localAuth(() => '').then(val => {

    // val is type (string | null)
    
});

Live typescript playground example

More reading