【发布时间】:2020-06-11 08:44:08
【问题描述】:
我正在构建一个对象模式验证函数,并且我正在尝试使返回类型动态匹配输入参数的结构。
// ----- Types
interface SchemaString {
type?: 'string',
required?: boolean,
default?: string
}
interface SchemaNumber {
type?: 'number',
required?: boolean,
default?: number
}
interface SchemaObject {
type?: 'object',
required?: boolean,
default?: {}
children?: Schema
}
type Schema = {[key:string]: SchemaString | SchemaNumber | SchemaObject};
// ----- Example
// Stuff happens here
function check<T extends Schema>(schema: T): Magic_Type<T>{
// Processing
}
const schema: Schema = {
foo: {
type: 'string'
}
bar: {
type: 'object',
children: {
baz: {type: 'string'}
}
}
};
const result = check(schema);
// 'result' type should be:
//
// {
// foo: string
// bar: {
// baz: string
// }
// }
//
主要目标是让 IDE 执行正确的自动完成,具体取决于输入的结构(并避免 {[key:string]: unknown}):
我尝试了以下类型的转换器,但它没有按预期工作:
type Magic_Type<T extends Schema> = {
[P in keyof T]: typeof T[P]['default']
}
感谢您的宝贵时间!
【问题讨论】:
标签: typescript dynamic types casting transformation