karsh
karsh

Reputation: 29

typescript class method definition using interface

I have a interface export from other package, and I need to implement it using class. However typescript can not auto infer the parameter type. Is there any way to get the method parameter automatically by ts ?

interface Interface {
    hello(param: {a: number}): void
}

class A implements Interface {
    hello(param) { // param is any
// how can i get the param type automatically ? 
    }
}


const B : Interface  = {
    hello(param) {// {a: number}

    }
}

Upvotes: 0

Views: 412

Answers (1)

spender
spender

Reputation: 120518

https://www.typescriptlang.org/docs/handbook/2/classes.html#cautions mentions this very issue. Quoting directly from the docs:

A common source of error is to assume that an implements clause will change the class type - it doesn’t!

interface Checkable {
  check(name: string): boolean;
}
 
class NameChecker implements Checkable {
  check(s) {
// Parameter 's' implicitly has an 'any' type.

    // Notice no error here
    return s.toLowercse() === "ok";
                 
// any
  }
}

In this example, we perhaps expected that s’s type would be influenced by the name: string parameter of check. It is not - implements clauses don’t change how the class body is checked or its type inferred.

Upvotes: 1

Related Questions