我使用简单模式在对象中定义DB模式:
{
name: 'string',
age: 'integer',
...
}
是否有可能从这个对象创建一个接口或类,这样我就不必键入所有内容两次?
我使用简单模式在对象中定义DB模式:
{
name: 'string',
age: 'integer',
...
}
是否有可能从这个对象创建一个接口或类,这样我就不必键入所有内容两次?
你可以这样做,但这可能会比它的价值更麻烦,除非你认为你可能会改变模式.TypeScript没有以您想要的方式推断类型的内置方法,因此您必须哄骗它这样做:
首先,定义一种将文字名称'string'
和'integer'
映射到它们所代表的类型脚本类型的方法(可能分别是string
和number
):
type MapSchemaTypes = {
string: string;
integer: number;
// others?
}
type MapSchema<T extends Record<string, keyof MapSchemaTypes>> = {
-readonly [K in keyof T]: MapSchemaTypes[T[K]]
}
现在,如果您可以获取一个适当类型的模式对象,比如您指定的对象,并从中获取关联的类型:
const personSchema = {name: 'string', age: 'integer'};
type Person = MapSchema<typeof personSchema>; // ERROR
哎呀,问题是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};
但现在感觉你在重复自己.幸运的是,有一种方法可以迫使它推断出正确的类型:
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};
更新2020-06:在更新的TS版本中,您可以使用const
assertion来获得相同的结果:
const personSchema = { name: 'string', age: 'integer' } as const;
type Person = MapSchema<typeof personSchema>;
真管用!
请看《行动on the Typescript Playground》.希望有帮助;祝你好运