5

I noticed that when implementing a generic interface (or class) and explicitly stating the types of those generics, the parameter types for functions inside the subclass are not inferred.

interface MyInterface<T> {
    open(data: T): void
}

class MyClass implements MyInterface<string> {
    open(data) {
        // Data should be string, but is any
    }
}

The current correct way to do this would be the following:

open(data: string) {
    ...
}

However, this forces me to enter the type multiple times which seems unnecessary. The following produces an error (which is expected):

open(data: number) {
    ...
}

Any type that isn't string gives an error, so shouldn't the compiler be able to infer that the type is string?

Viktor W
  • 1,139
  • 6
  • 9
  • Is this a problem with Typescript itself or the IDE/plugin you're using? – Abion47 Aug 31 '18 at 23:17
  • Yet return value _is_ checked: `open(): T` gives error because of `return 7`. Interesting. – raina77ow Aug 31 '18 at 23:20
  • I'd guess it's a problem with Typescript itself. Try pasting the code in the playground: http://www.typescriptlang.org/play/index.html – Viktor W Aug 31 '18 at 23:20
  • 1
    Known issue, see https://github.com/Microsoft/TypeScript/issues/16590 and https://github.com/Microsoft/TypeScript/issues/1373, the last one marked as 'design limitation' and 'won't fix' – artem Aug 31 '18 at 23:20

2 Answers2

5

This is a known issue in TypeScript that may be fixed at some point.

Matt McCutchen
  • 28,856
  • 2
  • 68
  • 75
2

As the other answer says, this is known issue with TypeScript compiler.

There is a way to provide implementation of MyInterface for which method parameters will be inferred, you just have to use a function that returns an object instead of a class:

interface MyInterface<T> {
    open(data: T): void
}


function createMyObject(): MyInterface<string> {
    return {
        open(data) { // data type is inferred as string here
            const n = data.length;
        }
    }
}
artem
  • 46,476
  • 8
  • 74
  • 78