Typescript 的泛型参数必须要么不填要么填完整?这种情况怎么处理?

2021-01-20 19:18:11 +08:00
 love
class Model {
    a!: number
    b!: string
}

class ModelB extends Model {
    c!: boolean
}

declare function getData<R, M extends Model>(m: M, field: keyof M): R

// 这里我希望 M 参数自动取自第一个参数,然后可以指定一个返回值类型为 number 。
// 可是似乎做不到?报缺一个泛型参数错误
let r = getData<number>(new ModelB(), 'c')

Playground

1468 次点击
所在节点    TypeScript
3 条回复
codehz
2021-01-20 19:29:03 +08:00
youmoo
2021-04-16 18:09:32 +08:00
其实你可以这样调用:

let r: number = getData(new ModelB(), 'c');
love
2021-04-17 16:35:14 +08:00
@youmoo 这似乎只是把类型换了个位置,还是要写的啊

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

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

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

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

© 2021 V2EX