How to declare interface with property is object with properties reduced from array in Typescript?

63 views Asked by At

Say I have this signature for a method:

interface MyClass<T> {
    data: T
}

create(options: {
  fields: (string | { name: string, type?: string})[],
  [key: string]: any
}): MyClassConstructor<T extends from_some_magic_extracting_fields_out>

What will happen at run time is while looping through fields in options, if it's a string, will create property name with the same string value, otherwise, get from name property.

How do I do this in Typescript interface to provide intellisense for my JS ?

Edit 1: Usage example

window.RecordCreator = function(opts) {
  var dataCfg = opts.fields.reduce(function(cfg, field) {
    if (typeof field === 'string') {
      cfg.push({ name: field, type: 'string' });
    } else {
      cfg.push({ name: field.name, type: field.type });
    }
    return cfg;
  }, []);
  // More stuff here to setup prototype for RecordConstructor
  return function RecordConstructor() {
    this.data = dataCfg.slice(0);
  }
}
0

There are 0 answers