Typescript动态创建界面

Chr*_*ris 6 javascript typescript

我使用simple-schema在对象中定义DB模式:

{
   name: 'string',
   age: 'integer',
   ...
}
Run Code Online (Sandbox Code Playgroud)

是否有可能从这个对象创建一个接口或类,所以我不必两次输入所有内容?

jca*_*alz 18

你可以做到这一点,但除非你认为你可能正在改变架构,否则它可能比它的价值更麻烦.TypeScript没有以您想要的方式推断类型的内置方法,因此您必须哄骗并哄骗它才能这样做:


首先,定义映射文字名称的方法'string''integer'其所代表的打字稿类型(大概stringnumber分别地):

type MapSchemaTypes = {
  string: string;
  integer: number;
  // others?
}
type MapSchema<T extends Record<string, keyof MapSchemaTypes>> = {
  [K in keyof T]: MapSchemaTypes[T[K]]
}
Run Code Online (Sandbox Code Playgroud)

现在,如果您可以采用类似于您指定的类型的适当类型的架构对象,并从中获取关联的类型:

const personSchema = {name: 'string', age: 'integer'}; 
type Person = MapSchema<typeof personSchema>; // ERROR
Run Code Online (Sandbox Code Playgroud)

哎呀,问题是personSchema被推断为{name: string; age: string}而不是期望的{name: 'string'; age: 'integer'}.您可以使用类型注释修复它:

const personSchema: { name: 'string', age: 'integer' } = { name: 'string', age: 'integer' }; 
type Person = MapSchema<typeof personSchema>; // {name: string; age: number};
Run Code Online (Sandbox Code Playgroud)

但现在感觉就像是在重复自己.幸运的是,有一种方法可以强制它推断出正确的类型:

function asSchema<T extends Record<string, keyof MapSchemaTypes>>(t: T): T {
  return t;
}
const personSchema = asSchema({ name: 'string', age: 'integer' }); // right type now
type Person = MapSchema<typeof personSchema>; // {name: string; age: number};
Run Code Online (Sandbox Code Playgroud)

这样可行!


在Typescript Playground上查看它.希望有所帮助; 祝好运!