Typescript : Omit a property in an interface, when another property within the same interface equals a certain value from an enum

Viewed 129

I would like to 'Omit' a property in an interface when another property within that same interface equals a certain value in an enum. This however DictionaryValue['type'] extends FieldType.ARRAY always equals to false.

I don't want to make the property optional by default as this would possibly result to type errors in my code.

enum FieldType {
  STRING,
  NUMBER,
  ARRAY
}

interface DictionaryValue {
  type: FieldType,
  value: number
}

interface Dictionary<T extends string> {
  [key in T]: DictionaryValue['type'] extends FieldType.ARRAY ?
    Omit< DictionaryValue, 'value'> :
    DictionaryValue
}
1 Answers

DictionaryValue['type'] will always be FieldType. A type is defined as is, not as to what might be in it when you declare a variable of the type.

You should consider having an union for DictionaryValue that contains the actual types you want for the values in the dictionary:

type DictionaryValue = {
    type: Exclude<FieldType, FieldType.ARRAY>,
    value: number
} | {
    type: FieldType.ARRAY
}

Playground Link

Related