首页 > 解决方案 > fn 重载的空类型保护

问题描述

我可以在 Typescript 中做一个重载,cb其中说如果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
   }

标签: typescript

解决方案


推荐阅读