您可以将以下代码放入foo.ts文件中。我正在尝试动态生成类型。我正在做的事就是基于这个问题: 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.
时,什么都没有显示。
答案 0 :(得分:2)
这里是一个使用Typescript 3和一个对象作为输入的示例。我在自己的项目中执行了与此类似的操作,以从我的Postgres数据库中为knex.js生成类型化查询构建器包装器。
// 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);
这是使用当前界面的一种方式:
// 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);
答案 1 :(得分:2)
假定您将name
属性的第一个元素用作要添加到结果类型的实际键,则定义有些不同。我将其修复为:
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']]
}
差异:
我仍在使用K extends string
来推断asOptions
中的字符串文字。在places中,TypeScript推断字符串文字,而在其他地方,它仅推断string
,而K extends Array<string>
不会推断字符串文字。因此,K
仍然是字符串类型,而我将name
属性设置为{0: K}
,这将确保它检查数组的第一个元素。
同样在OptionsToType
中,K
是字符串文字,因此必须提取以T['number']
作为{的第一个元素的K
{1}}属性,即name
。
其余部分现在应该可以工作了,我认为。希望能有所帮助。祝你好运。