diff --git a/packages/inquirer/inquirer.test.ts b/packages/inquirer/inquirer.test.ts index d6684b9ee..d01bfe3de 100644 --- a/packages/inquirer/inquirer.test.ts +++ b/packages/inquirer/inquirer.test.ts @@ -519,6 +519,35 @@ describe('inquirer.prompt(...)', () => { expect(answers).toEqual({ name1: 'bar', name: undefined }); }); + it('should use `default` when passed along `choices`', async () => { + class FakeSelect { + constructor(question: QuestionMap['stubSelect']) { + expect(question.choices).toEqual([ + { name: 'A', value: 'A', checked: false }, + { name: 'B', value: 'B', checked: true }, + ]); + } + + run() { + return Promise.resolve(); + } + + close() {} + } + inquirer.registerPrompt('stubSelect', FakeSelect); + + const answers = await inquirer.prompt([ + { + type: 'stubSelect', + name: 'name', + message: 'message', + choices: ['A', 'B'], + default: ['B'], + }, + ]); + expect(answers).toEqual({ name: undefined }); + }); + it('should expose the Reactive interface', async () => { const spy = vi.fn(); diff --git a/packages/inquirer/src/types.ts b/packages/inquirer/src/types.ts index 61a45887b..7d92ce942 100644 --- a/packages/inquirer/src/types.ts +++ b/packages/inquirer/src/types.ts @@ -78,7 +78,11 @@ type QuestionWithGetters< >; export type UnnamedDistinctQuestion = - | QuestionWithGetters<'checkbox', Parameters[0], A> + | QuestionWithGetters< + 'checkbox', + Parameters[0] & { default: unknown[] }, + A + > | QuestionWithGetters<'confirm', Parameters[0], A> | QuestionWithGetters<'editor', Parameters[0], A> | QuestionWithGetters<'expand', Parameters[0], A> diff --git a/packages/inquirer/src/ui/prompt.ts b/packages/inquirer/src/ui/prompt.ts index 53ff33751..3a813e871 100644 --- a/packages/inquirer/src/ui/prompt.ts +++ b/packages/inquirer/src/ui/prompt.ts @@ -266,17 +266,28 @@ export default class PromptsRunner { let choices; if (Array.isArray(resolvedChoices)) { choices = resolvedChoices.map((choice: unknown) => { - if (typeof choice === 'string' || typeof choice === 'number') { - return { name: choice, value: choice }; - } else if ( - typeof choice === 'object' && - choice != null && - !('value' in choice) && - 'name' in choice - ) { - return { ...choice, value: choice.name }; + const choiceObj = + typeof choice !== 'object' || choice == null + ? { name: choice, value: choice } + : { + ...choice, + value: + 'value' in choice + ? choice.value + : 'name' in choice + ? choice.name + : undefined, + }; + + if ('value' in choiceObj && Array.isArray(defaultValue)) { + // Add checked to question for backward compatibility. default was supported as alternative of per choice checked. + return { + checked: defaultValue.includes(choiceObj.value), + ...choiceObj, + }; } - return choice; + + return choiceObj; }); }