Typescript: classes don't inherit types from interfaces?

Viewed 39

I have some endpoint types that I want to share between the client and server:

type EndpointParams = {
    '/user': { userId: number },
    '/post': { postId: number },
};

On the server, I want to define endpoint controllers:

interface Endpoint<T extends keyof EndpointParams> {
    path: T;
    handleRequest(params: EndpointParams[T]): void;
}

class UserEndpoint implements Endpoint<'/user'> {
    path = '/user' as const;

    handleRequest({ userId }) {}
}

However, I get the Binding element 'userId' implicitly has an 'any' type.. Why doesn't TS automatically figure out that userId is a number? Shouldn't it get that from the interface?

TS Playground: https://www.typescriptlang.org/play?#code/C4TwDgpgBAogdgEzAewJZ2ABQIYCdsC2AzlALxQDeAUFLVAOQD0ArkRLvQFyVSvsCSCbnGYEARuygBfADQ06TFEWBceS4IOGiJuaXKkBuKlXTB2AM2wBjaACFsbeEjQYAPABUoEAB5nEJAGsIEGRzWEQUUxx8YgA+SnlaMGxgAAtudyM6KFTsRAAbCAAlCABHZghlAApkmKJuJ0iMaMIiAG13AF0ASm4ANzQEIyljK3yHEgBVNlxGl2AoVAIwQoIIDBJ7Rwj51yY+DnjqbOS0sgYWGfooBygrZDhlI0ScvIRCkvLK4CqKXhnBNJupQRlIgA

Some other related questions:

  1. Is it possible to omit the as const? Without it, I get Type 'string' is not assignable to type '"/user"'.
  2. Is it possible to infer the generic parameter like with functions?
  3. Is it possible to make path static? AFAIK interfaces don't support static.
0 Answers
Related