SBoudrias / Inquirer.js

A collection of common interactive command line user interfaces.
MIT License
20.21k stars 1.3k forks source link

How to get "Choice" type? #1491

Closed paul-uz closed 1 month ago

paul-uz commented 3 months ago

I need to tell a select prompt that my array for the choices option is an array of Choices, but its not working.

I need this type

type Choice<Value> = {
    value: Value;
    name?: string;
    description?: string;
    short?: string;
    disabled?: boolean | string;
    type?: never;
};

But using Choice<Value>[] isn't valid, as Value isn't exported? If I just use Choice[] then all the properties are required

SBoudrias commented 3 months ago

I think you'll loose type inference and the generic if you type it manually. I wouldn't recommend typing the choices array manually. Do you run into issues if you do? (code example could help too)

paul-uz commented 3 months ago

I'm not wanting to type it manually, I want to use the types defined in the library.

eg I have this code

const users = await cognito.getUsers(userPoolID as string);

const username = await select({
  message: 'User',
  choices: users,
});

const users should be an array of type Choice<Value> ie Choice<Value>[] but thats not valid.

SBoudrias commented 3 months ago

Can you post the typescript error you get?

paul-uz commented 3 months ago

First, trying to use Choice[], then trying to use Choice<Value>[]

Screenshot 2024-07-31 at 09 29 41 Screenshot 2024-07-31 at 09 30 02
medallyon commented 3 months ago

Could it be helpful to export the Choice type so that devs have access to it, similar to how we can do:

import type { Separator } from "@inquirer/prompts";
SBoudrias commented 3 months ago

@medallyon I don't really want to do that because then we tie type interfaces to our public APIs and to breaking changes. I don't believe the problem Paul is running into here is linked to the lack of exported Choice.

@paul-uz Can you remove the casting completely. I want to understand why the types aren't inferred properly - you shouldn't need to type it manually. I think you have more of an issue with the return type of cognito.getUsers than with inquirer - but with the types you added, we're burying this problem.

paul-uz commented 2 months ago

So I managed to get closer, ensuring I made my function return a type of (Separator | Choice<any>)[] but now get the error of Type '(Separator | Choice<any>)[]' is not assignable to type 'readonly (Separator | Choice<any>)[]'. so I guess I'm now blocked unless the types in the library are changed.

SBoudrias commented 2 months ago

@paul-uz can you send a minimal reproduction case? I'd be very happy to help, but it's really hard for me to provide help and direction without access to the exact code, and without being able to reproduce your issue.