Search code examples
typescripttsctypescript3.0

Conditional types with TypeScript


Say I have this:

type TypeMapping = {
  Boolean: boolean,
  String: string,
  Number: number,
  ArrayOfString: Array<string>,
  ArrayOfBoolean: Array<boolean>
}

export interface ElemType {
  foo: keyof TypeMapping,
  default: valueof TypeMapping
}

instead of using any for default, I want to conditionally define it, I tried this:

export interface ElemType<T extends TypeMapping> {
  foo: keyof T,
  default: T
}

but that doesn't seem quite right, does anyone know the right way to do this?

if it's not clear, for any given object that has type ElemType, the key that foo points to, must be matched by the value that foo points to. For example, this is valid:

{
  foo: 'String',
  default: 'this is a string'
}

but this is not:

{
  foo: 'Boolean',
  default: 'this should be a boolean instead'
}

so the type of the default field is conditional on the value/type of the type field.

Succintly, if foo is 'ArrayOfBoolean', then default should be: Array<boolean>. If foo is 'Number', then default should be number, if foo is 'Boolean' then default should be boolean, etc etc.


Solution

  • You can define ElemType as in Catalyst's answer and then use a mapped type to take the union of ElemType for all possible K:

    interface ElemType<K extends keyof TypeMapping> {
      foo: K;
      default: TypeMapping[K];
    }
    type ElemTypeMap = {[K in keyof TypeMapping]: ElemType<K>};
    // type ElemTypeMap = {
    //   Boolean: {foo: "Boolean", default: boolean},
    //   String: {foo: "String", default: string},
    //   ...
    // }
    type SomeElemType = ElemTypeMap[keyof TypeMapping];
    // Look up in ElemTypeMap by all keys and take the union:
    // {foo: "Boolean", default: boolean} | {foo: "String", default: string} | ...