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

请教一个关于正确声明范型的问题

  •  
  •   SilentDepth · 2020-12-22 01:10:39 +08:00 · 1385 次点击
    这是一个创建于 1193 天前的主题,其中的信息可能已经有所发展或是发生改变。

    我也不知道如何简短地在标题描述这个问题,只好直接上代码了。

    假设有如下第三方模块提供的类型定义:

    type Req = {
        url: string
        query: {[key: string]: string | string[]}
        body: {[key: string]: string | number | boolean}
    }
    
    type Handler = (req: Req) => void
    

    可以看到这个第三方模块对 querybody 只定义了通用类型。现在我想明确其结构,便于业务代码的编写,用起来就像这样:

    type Scheme1 = {
        query: {
            id: string
        }
    }
    
    const h1 = createHandler<Scheme1>(req => {
        const {query: {id}} = req
        console.log(id)
    })
    

    于是我需要实现那个 createHandler

    function createHandler <T extends Partial<Req>>(
        handler: (payload: Req & T) => void
    ): Handler {
        return handler // (a)
    }
    

    然而 TS 在 (a) 行报错了:

    'Req' is assignable to the constraint of type 'T', but 'T' could be instantiated with a different subtype of constraint 'Partial<Req>'. (2322)

    但如果忽略这个错误,整个代码是可以正常工作的,在 h1 中对 id 的类型推断也完全正常。我感觉范型定义那里不应该这么写,但没有思路,特来求教大家。

    🧪 Playground

    目前尚无回复
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1157 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 18:30 · PVG 02:30 · LAX 11:30 · JFK 14:30
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.