Zen-Ventzi-Marinov
Zen-Ventzi-Marinov

Reputation: 4236

Typescript class doesn't impelement interface types

interface IFoo {
  method: (ha: string) => void;
}

class Foo implements IFoo {
  public method(ha) {}
}

Hovering the 'ha' parameter in the class method says

Parameter 'ha' implicitly has an 'any' type, but a better type may be inferred from usage

Since the class impelements the interface, isn't it supposed to match the interface types? If you try to give parameter 'ha' a different type from string, say number, it, it errors that it's not assignable to type string, which makes sense.

So, why do I need to assign the type of ha both in the interface and in the class? Is this intended behaviour?

Upvotes: 5

Views: 531

Answers (1)

unional
unional

Reputation: 15589

Currently, TypeScript does not support that.

You can learn more about it here: https://github.com/Microsoft/TypeScript/issues/23911

This is not a simple task.

This is because TypeScript is built on top of JavaScript and there is no interface resolution like other languages such as C#.

To give you some basic idea, imagine you have two interfaces X and Y both have the same method but different types:

interface X { foo(i: string): string }
interface Y { foo(x: number): number }

When creating a class that implements both of these interfaces, you cannot just combine the interfaces together like this:

class K implements X, Y {
  // error: this does not satisfy either interfaces.
  foo(x: number | string): number | string {
    return x
  }
}

For this simple example, you need to:

class K implements X, Y {
  foo(x: number): number
  foo(x: string): string
  foo(x: number | string): number | string {
    return x
  }
}

And even that is not ideal, because it does not enforce the input type will match the output type.

Upvotes: 5

Related Questions