根据动态(映射/条件)类型获取类型完成 [英] Get type completion based on dynamic (mapped/conditional) type

查看:85
本文介绍了根据动态(映射/条件)类型获取类型完成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您可以将以下代码放入foo.ts文件中.我正在尝试动态生成类型.我正在做的事就是基于这个问题: 将数组映射到接口

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);

我没有得到任何类型的补全-当我键入v.时,什么都没有显示.

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

推荐答案

下面是一个使用Typescript 3和一个对象作为输入的示例.我在自己的项目中执行了与此非常相似的操作,以从我的Postgres数据库中为knex.js生成类型化的查询构建器包装器.

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);

这篇关于根据动态(映射/条件)类型获取类型完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆