V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
SilentDepth

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

  •  
  •   SilentDepth · Dec 22, 2020 · 1939 views
    This topic created in 1960 days ago, the information mentioned may be changed or developed.

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

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

    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

    No Comments Yet
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   2489 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 54ms · UTC 15:39 · PVG 23:39 · LAX 08:39 · JFK 11:39
    ♥ Do have faith in what you're doing.