ashays
ashays

Reputation: 1154

Automatically inferring types from overridden interfaces in 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;
}

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();
  }
}

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.

Upvotes: 5

Views: 893

Answers (1)

basarat
basarat

Reputation: 275849

Contextual typing of implemented properties is not supported.

More

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

Upvotes: 1

Related Questions