Typescript: Get correct answers type from inquirer questions array

602 Views Asked by At

I have an inquirer questions array like the following:

const prompts = [
    {
        type: 'input',
        name: 'foo',
        message: 'Enter a string',
    },
    {
        type: 'number',
        name: 'bar',
        message: 'Enter a number',
    },
] as const;

I would like to obtain the type of the answers object that inquirer is going to give me after calling prompt(). My current approach looks like this:

import { Question } from 'inquirer';

export type PromptAnswersFor<T extends ReadonlyArray<Question>> = {
    [key in T[number]['name']]: string;
                                ^^^^^^
//            what do I need to put here to make it work?
};

However, I don't know how to type the value on the right-hand side of the PromptAnswersFor type. At the moment it will always go to string.

Ideally, I'd want PromptAnswersFor<typeof prompts> to be { foo: string; bar: number }. I'm pretty sure it's possible, but I don't know how?

Edit: I'm able to infer the answer type for a single question like this:

type AnswerType<Q extends { type: string }> = Q extends { type: 'input' } ? string
                                            : Q extends { type: 'number' } ? number
                                            : Q extends { type: 'password' } ? string
                                            : Q extends { type: 'confirm' } ? boolean
                                            : never;

const inputQuestion = { type: 'confirm' } as const;
type T = AnswerType<typeof inputQuestion>
// -> boolean
0

There are 0 best solutions below