skip to Main Content
exports interface dev {
    print(
        a: string,
        b: string
    ):Promise<class bb>;
}



export function printInstance: dev {

   return new(class implements dev {

    public async print(
        C: string
    ): Promise<class bb> {

    }
})()
}

In interface there is two input a and b but in implementation another input c is introduced which doesn’t match with name in interface and only one is send. Will it cause any issues? I tried this and no error was thrown I guess name of variable doesn’t matter and if we pass less parameters then then the other one will take null value.

2

Answers


  1. Typescript uses structural typing to determine type compatibility. For functions this means that you don’t need to have the exact same signature for the declaration and the implementation, as long as the compiler can determine the implementation to be safe to call through the declaration.

    In this case this boils down to, a function with less parameters can be an implementation for a function declaration with more parameters as the extra passed in parameters will be ignored by the implementation, so no runtime error can occur because of this (for the most cases anyway, there might be corner cases on things that depend on Function.length)

    It means Typescript doesn’t check arg types or even count)

    Login or Signup to reply.
  2. Your provided code seems to have syntax issues,

    export interface Dev {
        print(a: string, b: string): Promise<Bb>;
    }
    
    class Bb {}
    
    export const printInstance: Dev = {
        async print(c: string, d?: string): Promise<Bb> {
          
            return new Bb();
        }
    }

    I made the second parameter (d) optional by using the ? syntax. This means you can call the print method with one or two parameters. If you only pass one parameter, the second one (d) will be undefined.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search