diff --git a/types/argparse/argparse-tests.ts b/types/argparse/argparse-tests.ts index ed714ada95..942e2bb4f2 100644 --- a/types/argparse/argparse-tests.ts +++ b/types/argparse/argparse-tests.ts @@ -1,6 +1,12 @@ // near copy of each of the tests from https://github.com/nodeca/argparse/tree/master/examples -import { ArgumentParser, RawDescriptionHelpFormatter } from 'argparse'; +import { + ArgumentParser, + RawDescriptionHelpFormatter, + Action, + ActionConstructorOptions, + Namespace, +} from 'argparse'; let args: any; const simpleExample = new ArgumentParser({ @@ -276,3 +282,26 @@ group.addArgument(['--bar'], { help: 'bar help' }); formatterExample.printHelp(); + +class CustomAction1 extends Action { + constructor(options: ActionConstructorOptions) { + super(options); + } + call(parser: ArgumentParser, namespace: Namespace, values: string | string[], optionString: string | null) { + console.log('custom action 1'); + } +} + +class CustomAction2 extends Action { + call(parser: ArgumentParser, namespace: Namespace, values: string | string[], optionString: string | null) { + console.log('custom action 2'); + } +} + +const customActionExample = new ArgumentParser({ addHelp: false }); +customActionExample.addArgument('--abc', { + action: CustomAction1, +}); +customActionExample.addArgument('--def', { + action: CustomAction2, +}); diff --git a/types/argparse/index.d.ts b/types/argparse/index.d.ts index 3330055b1f..a229b6bc49 100644 --- a/types/argparse/index.d.ts +++ b/types/argparse/index.d.ts @@ -3,6 +3,7 @@ // Definitions by: Andrew Schurman // Tomasz Łaziuk // Sebastian Silbermann +// Kannan Goundan // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.2 @@ -79,13 +80,24 @@ export interface ArgumentGroupOptions { description?: string; } +export abstract class Action { + protected dest: string; + constructor(options: ActionConstructorOptions); + abstract call(parser: ArgumentParser, namespace: Namespace, values: string | string[], optionString: string | null): void; +} + +// Passed to the Action constructor. Subclasses are just expected to relay this to +// the super() constructor, so using an "opaque type" pattern is probably fine. +// Someone may want to fill this out in the future. +export type ActionConstructorOptions = number & {_: 'ActionConstructorOptions'}; + export class HelpFormatter { } export class ArgumentDefaultsHelpFormatter { } export class RawDescriptionHelpFormatter { } export class RawTextHelpFormatter { } export interface ArgumentOptions { - action?: string; + action?: string | { new(options: ActionConstructorOptions): Action }; optionStrings?: string[]; dest?: string; nargs?: string | number; diff --git a/types/argparse/tsconfig.json b/types/argparse/tsconfig.json index 49e7b03ca8..9248f1d078 100644 --- a/types/argparse/tsconfig.json +++ b/types/argparse/tsconfig.json @@ -21,4 +21,4 @@ "index.d.ts", "argparse-tests.ts" ] -} \ No newline at end of file +}