0

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}

    }
}
1
  • I'm not sure if it's related, but typescript allows defining a different signature for the class: playground example. Maybe (!) that's the reason it wants you to be explicit Commented Aug 31, 2021 at 12:30

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.