Fn重载导致的空类型防护

时间:2019-11-29 01:20:35

标签: typescript

我可以在cb的Typescript中进行重载吗?它表示如果Error为空,则必须定义Id,或者如果定义了Error,则必须Id为空?

    function passId(cb: (err: Error, id: null) => void): any
    function passId(cb: (err: null, id: number) => void): any
    function passId(cb: (err: Error | null, id: number | null) => void){
        // implementation ...
     }


    // usage: if error defined and the fn returns 
    // then it means because of the type definition number must be defined.

   const foo = () => {
      if(err){
        return
      }

      // id must be defined by here..
      let a: number = id
   }

0 个答案:

没有答案