Motivation for Using Object Parameters
One of the motivations behind using objects as function parameters is to allow the caller to clearly define arguments with specified field names, which can make code reviews easier.
Challenge When Using Implements and Extends
However, dealing with object parameters in conjunction with implements
and extends
can become cumbersome. This is currently a challenge that I am facing in my code implementation.
src/domain/ServiceInterface.ts
export interface ServiceInterface {
doesThings(args: {
awesomeFieldName: string;
isThisAwesomeFieldName?: string;
ohWaitMoreAwesomeFieldName?: string;
}): boolean;
src/domain/ComposedServiceInterface.ts
import { ServiceInterface } from "./domain/ServiceInterface";
export type ComposedServiceInterface = ServiceInterface & { hello: () => string };
src/implementations/ComposedServiceImplementation.ts
import { ComposedServiceInterface } from "./domain/ComposedServiceInterface";
export class ComposedServiceImplementation implements ComposedServiceInterface {
doesThings(args: {
awesomeFieldName: string;
isThisAwesomeFieldName?: string;
ohWaitMoreAwesomeFieldName?: string;
}): boolean {
return true;
}
}
Various Approaches Taken
1. Using type
/ interface
for Object Parameter
src/domain/ServiceInterface.ts
export type DoesThingsParameter = {
awesomeFieldName: string;
isThisAwesomeFieldName?: string;
ohWaitMoreAwesomeFieldName?: string;
};
export interface ServiceInterface {
doesThings(args: DoesThingsParameter): boolean;
src/domain/ComposedServiceInterface.ts
import { ServiceInterface } from "./domain/ServiceInterface";
export type ComposedServiceInterface = ServiceInterface & { hello: () => string };
src/implementations/ComposedServiceImplementation
import { ComposedServiceInterface } from "./domain/ComposedServiceInterface";
import { DoesThingsParameter } from "./domain/ServiceInterface";
export class ComposedServiceImplementation implements ComposedServiceInterface {
doesThings(args: DoesThingsParameter): boolean {
return true;
}
}
Concern: The use of import
in
src/implementations/ComposedServiceImplementation
might not be necessary since it only implements ComposedServiceInterface
2. Exploring Utility Types such as Parameter
Reference: https://www.typescriptlang.org/docs/handbook/utility-types.html#parameterstype
I have encountered challenges in getting TypeScript to accept a Class method like
Parameter<ComposedServiceInterface.doesThings>
. Any advice or insights on this would be appreciated.