Get type completion based on dynamic (mapped/condi

2019-06-05 20:21发布

问题:

You can drop the following code into a foo.ts file. I am trying to dynamically generate types. What I am doing is based off this question: Map array to an interface

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

export enum Type {
  Boolean = 'Boolean',
  String = 'String',
  Number = 'Number',
  ArrayOfString = 'ArrayOfString'
}

const asOptions = <K extends Array<string>, T extends Array<{ name: K, type: keyof TypeMapping }>>(t: T) => t;

type OptionsToType<T extends Array<{ name: Array<string>, type: keyof TypeMapping }>>
  = { [K in T[number]['name'][0]]: TypeMapping[Extract<T[number], { name: K }>['type']] }


const options = asOptions([
  {
    name: ['foo'],
    type: Type.Boolean
  },

  {
    name: ['bar'],
    type: Type.String
  },

  {
    name: ['baz'],
    type: Type.Number
  },

  {
    name: ['bab'],
    type: Type.ArrayOfString
  }
]);



export type Opts = OptionsToType<typeof options>;

const v = <Opts>{foo: true};  // this does not compile

console.log(typeof v.foo);

I don't get any type completion - when I type v. nothing shows up.

回答1:

Assuming you are using the first element of the name property as the actual key to add to the resultant type, your definitions are a little off. I would fix them to be:

const asOptions = <
  K extends string, 
  T extends Array<{ name: {0: K}, type: keyof TypeMapping }>
>(t: T) => t;

type OptionsToType<T extends Array<{ name: Array<string>, type: keyof TypeMapping }>> = {
  [K in T[number]['name'][0]]: TypeMapping[Extract<T[number], { name: {0: K} }>['type']] 
}

The differences:

  • I am still using K extends string to induce inference of a string literal in asOptions. There are places where TypeScript infers string literals and other places where it infers just string, and K extends Array<string> will not infer a string literal. So K is still a string type, and instead I've made the name property as {0: K} which will ensure that it inspects the first element of the array.

  • Again in OptionsToType, K is a string literal, so you must extract the piece of T['number'] that has K as the first element of the name property, which is Extract<T[number], {name: {0: K} }>.

The rest should work now, I think. Hope that helps. Good luck.



回答2:

Here is an example that uses Typescript 3, and an object as the input. I do something very similar to this in my own projects to generate a typed query builder wrapper for knex.js from my Postgres database.

// for lazier enum/mapping declaration
function StrEnum<T extends string[]>(...values: T) {
  let o = {};
  for (let v in values) {
    o[v] = v;
  }
  return o as { [K in T[number]]: K };
}
// declare enum values
const Type = StrEnum("Boolean", "String", "Number", "ArrayOfString");

// correlate the keys to things
type TypeMapping = {
  Boolean: boolean;
  String: string;
  Number: number;
  ArrayOfString: Array<string>;
};

// thing to convert your generated interface into something useful
const asOptions = <T extends { [key: string]: keyof TypeMapping }>(t: T) => t;

// the generated object
const options = asOptions({
  foo: Type.Boolean,
  bar: Type.String,
  baz: Type.Number,
  bab: Type.ArrayOfString
});

type Opts = Partial<
  { [V in keyof typeof options]: TypeMapping[typeof options[V]] }
>;

const v: Opts = { foo: true }; // this does compile

console.log(v);

Here is a way to use your current interface:

// for lazier enum/mapping declaration
function StrEnum<T extends string[]>(...values: T) {
  let o = {};
  for (let v in values) {
    o[v] = v;
  }
  return o as { [K in T[number]]: K };
}
// declare enum values
const Type = StrEnum("Boolean", "String", "Number", "ArrayOfString");

// correlate the keys to things
type TypeMapping = {
  Boolean: boolean;
  String: string;
  Number: number;
  ArrayOfString: Array<string>;
};

type OptDefinitionElement<K extends string, V extends keyof TypeMapping> = {
  name: K;
  value: V;
};

// thing to convert your generated interface into something useful
const asOptions = <T extends OptDefinitionElement<any, any>[]>(...t: T) => {
  return t;
};

// because typescript doesn't like to infer strings
// nested inside objects/arrays so precisely
function InferString<S extends string>(s: S) {
  return s;
}

// the generated object
const options = asOptions(
  { name: InferString("foo"), value: Type.Boolean },
  { name: InferString("bar"), value: Type.String },
  { name: InferString("baz"), value: Type.Number },
  { name: "bab" as "bab", value: Type.ArrayOfString } // note you don't *have* to use the Infer helper
);

// way to iterate keys and construct objects, and then result in the | type of all
// of the values
type Values<T extends { [ignoreme: string]: any }> = T extends {
  [ignoreme: string]: infer R;
}
  ? R
  : never;
type OptionsType = typeof options;
type OptionKeys = Exclude<keyof OptionsType, keyof Array<any>>;
type Opts = Values<
  {
    [TupleIndex in Exclude<keyof OptionsType, keyof Array<any>>]: {
      [key in OptionsType[TupleIndex]["name"]]: TypeMapping[OptionsType[TupleIndex]["value"]]
    }
  }
>;

const v: Opts = { foo: true }; // this does compile

console.log(v);