简体   繁体   English

扩展 Typescript 接口时推断泛型参数

[英]Infer generic argument when extending a Typescript interface

I have an interface which requires a generic variable:我有一个需要通用变量的interface

interface Action<T extends string> {
   type: T
}

I am able to extend it when I set the value of the generic:当我设置泛型的值时,我可以扩展它:

interface SomeAction extends Action<"something"> {
}

I would like to infer the generic automatically, but I get an error when I try this:我想自动推断泛型,但是当我尝试这样做时出现错误:

interface SomeAction extends Action {
   type: "something"
}

Error TS2314: Generic type 'Action' requires 1 type argument(s).错误 TS2314:通用类型“操作”需要 1 个类型参数。

I'd like the second example to infer its type automatically.我希望第二个示例自动推断其类型。 Is this possible?这可能吗?

Just specify default value for T and it should work:只需为T指定默认值,它应该可以工作:

interface Action<T extends string = string> {}

Playground Link 游乐场链接

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM