diff --git a/src/utils.ts b/src/utils.ts index 1ce99e03..706266d6 100644 --- a/src/utils.ts +++ b/src/utils.ts @@ -128,7 +128,7 @@ export function setByType( transforms: { [k: string]: any }, ): void { for (const [key, transform] of Object.entries(transforms)) { - if (transform.shouldTransform) { + if (transform.shouldTransform && Object.hasOwn(obj, key)) { obj[key] = [obj[key]].flat() if (typeof transform.transformFunction === 'function') { diff --git a/tests/index.test.ts b/tests/index.test.ts index bbb176b4..d97b8917 100644 --- a/tests/index.test.ts +++ b/tests/index.test.ts @@ -151,6 +151,23 @@ test('array types with transformFunction', () => { expect(options.scale).toEqual(true) }) +test('omitted array option stays absent when another option is passed', () => { + const cli = cac() + .option('--type ', 'Choose a project type', { + default: 'node', + }) + .option('--externals ', 'Add externals', { + type: [], + }) + + const { options: withoutOption } = cli.parse(['node', 'bin']) + expect(withoutOption).not.toHaveProperty('externals') + + const { options: withOption } = cli.parse(['node', 'bin', '--type', 'node']) + expect(withOption.type).toBe('node') + expect(withOption).not.toHaveProperty('externals') +}) + test('throw on unknown options', () => { const cli = cac()