Typescript conditional types for elements of an array

It seems like a simple task, but I'm having trouble finding the right configuration. My goal is to create a type for an array where each index corresponds to the "plugin" value provided (an enum) and maps to the types of options specific to that plugin. Here's an example:

enum Plugins {
   A = "A",
   B = "B",
   ... 
};

const allOptions = [
  { 
    plugin: Plugins.A,
    options: { 
      // miscellaneous, unique options for Plugin A
    }
  },
  {
    plugin: Plugins.B,
    options: { 
      // miscellaneous, unique options for Plugin B
    }
  },
  ...
]
  • Each plugin would have its own custom type for its unique options,
  • The array could be of any length and plugins could be added in any order,
  • There could be multiple entries for a single plugin.

The goal is for TypeScript to recognize whatever plugin the user provides for the "plugin" property in the array, and then validate that the options for that array index are of the correct type.

I've looked into TypeScript's conditional types documentation, but it doesn't seem to fully apply in this case.

Answer №1

If you're looking for a solution to this problem, here's one approach:

enum Plugins {
    A = "A",
    B = "B"
}

interface PluginA {
    plugin: Plugins.A
    options: {
        name: string
        codex: number
    }
}

interface PluginB {
    plugin: Plugins.B
    options: {
        name: string
        operations: boolean
    }
}

type PossiblePlugins = PluginA | PluginB

const allOptions: (PossiblePlugins)[] = [
    {
        plugin: Plugins.A,
        options: {
            name: 'Plugin A',
            codex: 1
        }
    },
    {
        plugin: Plugins.B,
        options: {
            name: 'plugin B',
            operations: true
        }
    },
]

console.log(allOptions)

Take a look at the sample code in the Typescript playground here. For more insights, check out the option recommended by jcalz, which may be better suited based on your experience level working with Typescript.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

RN TypeScript is handling parameters with an implicit any type

My React Native (RN) application includes the following code snippet: handleTextChange = e => { this.setState({ value: e }) } I am using TypeScript (TS) and it's giving me a warning saying, "parameter 'e' implicitly has 'any&apos ...

Define the data type of the array within hooks, then proceed with initialization

After attempting to populate the state using data fetched by RNFS.readDir, I encountered an issue where the state was being reinitialized. interface fileUnit { type: string, index: number, title: string, path: string, date: string, size: numbe ...

simulated function from a different module used for testing purposes

I'm currently using Chai and Mocha for testing purposes within my project. I am looking to test the createTreefromFolder function that resides in a module called tree.js: export function createTreefromFolder(path: string): string[] { const files = l ...

A Promise is automatically returned by async functions

async saveUserToDatabase(userData: IUser): Promise<User | null> { const { username, role, password, email } = userData; const newUser = new User(); newUser.username = username; newUser.role = role; newUser.pass ...

Learn the technique of passing dual onClick parameters to a single function in React

I am working on a function named Test where I need to pass two onClick references. const Test = ({ onConnect }:{ onConnect:any }, { onDisconnect }:{ onDisconnect:any }) => { return ( <div> <DrawDiagram /> <button onClick ...

How can I activate TypeScript interface IntelliSense for React projects in VSCode?

Did you know that there are TypeScript interfaces designed for DOM, ES5, and other JavaScript modules? I am curious if it is feasible to have intellisense similar to the one provided by TypeScript Playground for various interfaces in a React project. ...

When working with data in Angular, make sure to use any[] instead of any in app.component.html and app.component.ts to avoid causing overload errors

I'm new to working with Angular, specifically using Angular 15. I have a Rest API response that I need to parse and display in the UI using Angular. To achieve this, I employed the use of HttpClient for making GET requests and parsing the responses. ...

Detecting the check status of a checkbox in react native: a complete guide

I'm currently working on a scenario where I need to implement logic for checking or unchecking a checkbox in React Native. If the checkbox is checked, I want to print one string, and if it's unchecked, I want to print something else. How can I ac ...

update the value of a specific document in Firestore by specifying its

Is there a way to update document values in a Firestore collection for multiple records without manually specifying each document ID? Currently, I have a method that works for updating individual documents using their IDs, but what if I need to update a la ...

callbacks in amazon-cognito-identity-js

When working with amazon-cognito-identity-js, I encountered an issue with the callback function. This is what it currently looks like: cognitoUser?.getUserAttributes((err, results) => { if (err) { console.log(err.message || JSON.stringify(err)); ...

Using Angular 2 to assign a pipe dynamically from a variable

Could something like the following be achievable: {{property | some_variable_name}} I am aiming to utilize a pipe that is defined in a JSON configuration (or variable), but I am uncertain if it is feasible to include the pipe name within the interpolatio ...

Angular is having trouble locating the module for my custom library

Trying to implement SSR in my angular application, but encountering an error when running npm run build:ssr. I've created my own library named @asfc/shared, which is bundled in the dist folder. ERROR in projects/asfc-web/src/environments/environment. ...

Encountered an issue in Typescript with error TS2554: Was expecting 0 arguments but received 1 when implementing useReducer and useContext in React

I've encountered several errors with my useReducers and useContext in my project. One specific error (TS2554) that I keep running into is related to the AuthReducer functionality. I'm facing the same issue with each Action dispatch. I've tri ...

Navigating a faulty index.d.ts file that came with the npm package

Recently, I came across an npm package that did not have TypeScript but provided its own index.d.ts file. However, the types in this file were incorrect and contributed by someone who was not actively maintaining the package. When I attempted to reference ...

When the network connection is active, the observable will retry and repeat based on other observable signals

Sample snippet: const networkConnected = new BehaviorSubject<boolean>(false); setTimeout(networkConnected.next(true), 10000); webSocket('ws://localhost:4949') .pipe( retryWhen(errors => errors.pipe(delay(10000), filter(() => n ...

Tips for setting or patching multiple values in an ngselect within a reactive form

https://i.sstatic.net/ct6oJ.png I am facing an issue with my ng select feature that allows users to select multiple languages. However, upon binding multiple selected values in the ng select, empty tags are being displayed. I have included my code below. * ...

What is the reason for the component property being valued within the subscribe body when it is not defined outside of it?

I am currently facing an issue with retrieving data from a SQL server table using http.get within the constructor of an Angular component 5. While I am able to assign the retrieved data to a component property inside the subscribe method, the value becomes ...

Is there a way to determine the type of a method member within a class without the need to instantiate it?

Consider the following scenario: template <typename T> void foo(std::vector<T> &t) { auto var = T(); std::vector<decltype(var.Get())> array; } In this code snippet, an array is being created with a type determined by the ret ...

Having trouble with Angular routing when attempting to directly access a specific URL path?

Seeking help with my routing setup in Angular. Using v12 of Angular. Encountering a 404 Not Found error when trying to access the direct URL for "register" at somesite.com/register. Uncertain if this is a server or Angular issue. Here is my router module ...

Using Typescript with React and Redux Saga, we are accessing a single API endpoint to retrieve both paginated and non-paginated data

I've hit a roadblock while trying to call the API to fetch paginated data for viewing and non-paginated data for exporting as CSV Here's how Redux Saga is implemented: function* exportsearchPaymentRequests({ payload, type }: { payload: any ...