0

Seems like this should be simple but I can't hit on the right config. I'm trying to create a type for an array where each index maps the "plugin" value supplied (an enum) to the types for that particular plugin's options. Here's an example:

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

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

The point is, when a user defines the array I want TS to recognize whatever plugin they supplied for the "plugin" property, then validate the options for that array index has the right type.

I read over TS's conditional types doc, but it didn't seem to quite apply.

3
  • Could you give a minimal reproducible example that gives us the miscellaneous unique options so that we have something concrete to test against? Commented Nov 27, 2022 at 21:38
  • 2
    Is this approach what you're looking for or am I missing something? Commented Nov 27, 2022 at 21:42
  • That's precisely what I was looking for, thanks @jcalz! Interesting syntax on the Options line, I'll have to dig into it. Commented Nov 27, 2022 at 23:41

1 Answer 1

1

There are a bunch of ways to solve this but you could do something along the lines of this:

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)

Check it out in the Typescript playground here. The option suggested by jcalz is more ideal depending on the level of experience you have as a Typescript developer.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.