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

2020-12-22 01:10:39 +08:00
 SilentDepth

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

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

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

1415 次点击
所在节点    TypeScript
0 条回复

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/737669

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX