From 044806ac741b63b64b299b8571616be740132ff5 Mon Sep 17 00:00:00 2001 From: Francisco Giordano Date: Thu, 11 Jul 2019 19:04:43 -0300 Subject: [PATCH] fix: better type for flags with default value (#53) --- src/flags.ts | 8 +++++--- test/parse.test.ts | 8 ++++---- 2 files changed, 9 insertions(+), 7 deletions(-) diff --git a/src/flags.ts b/src/flags.ts index 77d9e0c..4088431 100644 --- a/src/flags.ts +++ b/src/flags.ts @@ -4,6 +4,8 @@ import {AlphabetLowercase, AlphabetUppercase} from './alphabet' export type DefaultContext = { options: IOptionFlag; flags: { [k: string]: string } } +export type Default = T | ((context: DefaultContext) => T) + export type IFlagBase = { name: string char?: AlphabetLowercase | AlphabetUppercase @@ -26,13 +28,13 @@ export type IBooleanFlag = IFlagBase & { /** * specifying a default of false is the same not specifying a default */ - default?: boolean | ((context: DefaultContext) => boolean) + default?: Default } export type IOptionFlag = IFlagBase & { type: 'option' helpValue?: string - default?: T | ((context: DefaultContext) => T | undefined) + default?: Default multiple: boolean input: string[] options?: string[] @@ -40,7 +42,7 @@ export type IOptionFlag = IFlagBase & { export type Definition = { (options: {multiple: true} & Partial>): IOptionFlag - (options: {required: true} & Partial>): IOptionFlag + (options: ({required: true} | {default: Default}) & Partial>): IOptionFlag (options?: Partial>): IOptionFlag } diff --git a/test/parse.test.ts b/test/parse.test.ts index 1e96f46..d642d5c 100644 --- a/test/parse.test.ts +++ b/test/parse.test.ts @@ -459,9 +459,10 @@ See more help with --help`) }) it('default has options', () => { + const def: flags.Default = ({options}) => options.description const out = parse([], { // args: [{ name: 'baz', default: () => 'BAZ' }], - flags: {foo: flags.string({description: 'bar', default: ({options}) => options.description})}, + flags: {foo: flags.string({description: 'bar', default: def})}, }) // expect(out.args).to.deep.include({ baz: 'BAZ' }) // expect(out.argv).to.deep.include(['BAZ']) @@ -469,12 +470,11 @@ See more help with --help`) }) it('can default to a different flag', () => { + const def: flags.Default = opts => opts.flags.foo const out = parse(['--foo=bar'], { flags: { bar: flags.string({ - default: opts => { - return opts.flags.foo - }, + default: def, }), foo: flags.string(), },