Skip to content
This repository has been archived by the owner on Aug 22, 2023. It is now read-only.

Commit

Permalink
fix: better type for flags with default value (#53)
Browse files Browse the repository at this point in the history
  • Loading branch information
frangio authored and RasPhilCo committed Jul 11, 2019
1 parent f3880ae commit 044806a
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 7 deletions.
8 changes: 5 additions & 3 deletions src/flags.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ import {AlphabetLowercase, AlphabetUppercase} from './alphabet'

export type DefaultContext<T> = { options: IOptionFlag<T>; flags: { [k: string]: string } }

export type Default<T> = T | ((context: DefaultContext<T>) => T)

export type IFlagBase<T, I> = {
name: string
char?: AlphabetLowercase | AlphabetUppercase
Expand All @@ -26,21 +28,21 @@ export type IBooleanFlag<T> = IFlagBase<T, boolean> & {
/**
* specifying a default of false is the same not specifying a default
*/
default?: boolean | ((context: DefaultContext<boolean>) => boolean)
default?: Default<boolean>
}

export type IOptionFlag<T> = IFlagBase<T, string> & {
type: 'option'
helpValue?: string
default?: T | ((context: DefaultContext<T>) => T | undefined)
default?: Default<T | undefined>
multiple: boolean
input: string[]
options?: string[]
}

export type Definition<T> = {
(options: {multiple: true} & Partial<IOptionFlag<T>>): IOptionFlag<T[]>
(options: {required: true} & Partial<IOptionFlag<T>>): IOptionFlag<T>
(options: ({required: true} | {default: Default<T>}) & Partial<IOptionFlag<T>>): IOptionFlag<T>
(options?: Partial<IOptionFlag<T>>): IOptionFlag<T | undefined>
}

Expand Down
8 changes: 4 additions & 4 deletions test/parse.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -459,22 +459,22 @@ See more help with --help`)
})

it('default has options', () => {
const def: flags.Default<string | undefined> = ({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'])
expect(out.flags).to.deep.include({foo: 'bar'})
})

it('can default to a different flag', () => {
const def: flags.Default<string | undefined> = opts => opts.flags.foo
const out = parse(['--foo=bar'], {
flags: {
bar: flags.string({
default: opts => {
return opts.flags.foo
},
default: def,
}),
foo: flags.string(),
},
Expand Down

0 comments on commit 044806a

Please sign in to comment.