Home > Mobile >  Conditional TS types for array items
Conditional TS types for array items

Time:11-28

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.

CodePudding user response:

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.

  • Related