从 TypeScript 中覆盖的接口自动推断类型

从 TypeScript 中覆盖的接口自动推断类型

问题描述:

我正在尝试为已经存在的模块创建一些 TypeScript 定义.在要实现的特定接口中,签名如下所示:

I'm trying to create some TypeScript definitions for modules that already exist. 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;
}

参数和返回结构是固定的,我真的很希望能够让 TypeScript 推断出我的重写方法的参数类型.但是,当我创建覆盖时,我看到参数隐式具有 any 类型.

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. However, when I create my override, I see that the parameter implicitly has an any type.

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

有什么方法可以将 getBodyClasses 标记为专用覆盖,以便自动推断参数类型?如果我将 next 输入为 number,它已经说明 Page 没有正确实现接口,所以我不太明白为什么它可以'然后推断 next 的类型与接口的相同.

Is there any way to mark getBodyClasses as a dedicated override so that the types for parameters are automatically inferred? 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.

不支持已实现属性的上下文类型.

Contextual typing of implemented properties is not supported.

跟踪此问题的主要问题是 https://github.com/Microsoft/TypeScript/问题/1373

The main issue that tracked this is https://github.com/Microsoft/TypeScript/issues/1373