Home > database >  Why my class method is not able to get the params types from its interface?
Why my class method is not able to get the params types from its interface?

Time:11-10

I wrote this code below to show my problem

type MyFunction<T> = (req: string, res: number) => T;

interface ITest {
  store: MyFunction<void>;
}

class Test implements ITest {
  store(req, res) { //req, res got implicit any type
      req.codePointAt()
      res.toFixed()
  }
}

Why when I implement my interface ITest on my class Test it still not being able to infer the params types ?

CodePudding user response:

store is not a function, is a property that has a type that is a function.

If you want to keep the type, you should declare it like so:

    class Test implements ITest {
      store: MyFunction<void> = (req, res) => {
          req.codePointAt();
          res.toFixed();
      }
    }

And now codePointAt wants a parameter :)

CodePudding user response:

I think this is what @jcalz meant, you still need to put the param and return type on the class method, but by implementing a interface, TypeScript will check whether the method have the same param and return type as the interface it implements

type MyFunction<T> = (req: string, res: number) => T;

interface ITest {
  store: MyFunction<void>;
}

class Test implements ITest {
  store(req: number, res: number): void {
  }
}

that code will shows an error because req type is incompatible

Property 'store' in type 'Test' is not assignable to the same property in base type 'ITest'.
  Type '(req: number, res: number) => void' is not assignable to type 'MyFunction<void>'.
    Types of parameters 'req' and 'req' are incompatible.
      Type 'string' is not assignable to type 'number'.

TS Playground

CodePudding user response:

An ITest.store must implement (req: string, res: number) => void;. Your Test's store method technically does that. Its signature is (req: any, res:any) => void. The any types both suffice for string and number.

When you use implements, your object/class/etc is agreeing to fulfill the interface's requirements. This means the interface isn't making any decisions about the types. Its the responsibility of the implementor. So back to above, Test agrees to implement the ITest interface. Its store method currently has a signature of (req: any, res: any) => void. Since any fulfills string and number it effectively fulfills the ITest interface.

  • Related