network icon indicating copy to clipboard operation
network copied to clipboard

chore: Add utility mapped type for Java-like enforcement of method parameter…

Open ptesavol opened this issue 2 years ago • 0 comments

Add Java-like type checking of method parameter types when implementing an interface, and when defining a callback.

Usage of strict interface implementation: class MyClass implements strictly<MyClass, MyInterface> { ... }

Results: shows readable compiler errors in IDE and compiler if the method signatures do not match exactly.

/**

Checks that the implementation of an interface has

the public methods defined in the interface with the exactly same

parameter types as the interface.

@param C - the class that implements the interface

@param I - the interface

@returns - an interface that is otherwise the same as I, but the methods

whose parameters do not match between C and I are marked with a type that

causes a compiler error when used in combination with the 'implements' keyword.

@example ts class MyClass implements strictly<MyClass, MyInterface> { ... } */

Usage of strictly typed callbacks:

/**

  • Ensures that the callback passed as an argument has exactly the same
  • parameter types as in the type definition. This utility type is
  • to be used in the definitions of functions that take callbacks as arguments.
  • No action from the callers of the function is required.
  • @param C - placeholder parameter for the type of the callback function passed as an argument
  • to the function call. NOTE: the function needs to be converted to a generic in order to use strictCb.
  • The compiler will automatically infer parameter C from the context when the function is called, and
  • the caller of the function does not need to know that the function is generic.
  • @param I - F the usual type definition of the callback function.
  • @returns - strict callback function type that causes a compiler error if the parameters
  • of the callback passed as an argument do not match exactly the parameters of the callback type definition
  • @example ts fetchValue<C>(callback: strictCb<C, (result: string) => void>): void { callback('some value') } */

ptesavol avatar Dec 15 '23 08:12 ptesavol