简体   繁体   English

在TypeScript中自动推断来自重写接口的类型

[英]Automatically inferring types from overridden interfaces in TypeScript

I'm trying to create some TypeScript definitions for modules that already exist. 我正在尝试为已经存在的模块创建一些TypeScript定义。 In a particular interface to be implemented, the signature looks like this: 在要实现的特定接口中,签名如下所示:

type NextFunction<T> = () => T;
type Response = string[] | Promise<string[]>;

interface IPage {
  getBodyClasses(next: NextFunction<Response>): Response;
}

The parameter and return structures are fixed, and I'd really like to be able to have TypeScript infer what the parameter types are of my overridden methods. 参数和返回结构是固定的,我真的希望能够让TypeScript推断我的重写方法的参数类型是什么。 However, when I create my override, I see that the parameter implicitly has an any type. 但是,当我创建覆盖时,我看到该参数隐式具有any类型。

class Page implements IPage {
  getBodyClasses(next) {
    return next();
  }
}

Is there any way to mark getBodyClasses as a dedicated override so that the types for parameters are automatically inferred? 有没有办法将getBodyClasses标记为专用覆盖,以便自动推断参数的类型? It would already say that Page was improperly implementing the interface if I typed next as number , so I don't quite understand why it can't also then infer the type of next is the same as the interface's. 如果我输入next作为number ,那么就已经说过Page正在不正确地实现接口,所以我不太明白为什么它也不能推断出next的类型和接口的类型相同。

Contextual typing of implemented properties is not supported. 不支持已实现属性的上下文类型。

More 更多

The main issue that tracked this is https://github.com/Microsoft/TypeScript/issues/1373 跟踪此问题的主要问题是https://github.com/Microsoft/TypeScript/issues/1373

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

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