V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
llej
V2EX  ›  TypeScript

#笔记#更好的 ts 重载声明方法

  •  
  •   llej · 37 天前 · 714 次点击
    这是一个创建于 37 天前的主题,其中的信息可能已经有所发展或是发生改变。
    /** 更新数据 */
    function fn(op:'updated',id:number):any
    /** 创建数据 */
    function fn(op:'created'):any
    /** 如果在上面的重载写了 jsdoc 那么这里的 jsdoc 将无法看到
     * 使用这种形式相比下面这种更常见的我感觉类型描述更准确一些
     * 并且上面两个重载声明也可以直接不用(但如果要针对不同重载写 jsdoc 的话还是要有重载声明的)
     * ```ts
     * function fn(op:'created'|'updated',id?:number){}
     * ```
     */
    function fn(...[op,id]:['created']|['updated',number]){
    }
    fn('created')
    fn('created',1) //Argument of type '"created"' is not assignable to parameter of type '"updated"'.
    fn('updated') //Argument of type '"updated"' is not assignable to parameter of type '"created"'.(2345)
    fn('updated',1)
    
    目前尚无回复
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   3256 人在线   最高记录 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 31ms · UTC 11:36 · PVG 19:36 · LAX 04:36 · JFK 07:36
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.