// Provided input
const input: Input = {
hello: {
type: "string",
},
first: {
second: {
type: "number"
}
}
}
// Expected output
const output = {
hello: "some-string",
first: {
second: 42
}
}
// Function that processes the input and spits out the expected output
function processInput<T extends Input>(input: T): Output<T> {
// Some logic
}
我想使用processInput
函数处理嵌套的input
对象,以生成类似output
对象的输出.这可以通过判断type
属性是否存在等简单地完成.
但我的"问题"是Output
型.我想根据提供的输入准确地输入输出.
这就是我到目前为止想出来的:
export type Property = { type: "string" } | { type: "number" };
export type Input = { [key: string]: Property | Input };
export type Output<T extends Input> = {
[Key in keyof T]:
T[Key] extends { type: "string" } ? string :
T[Key] extends { type: "number" } ? number :
T[Key] extends Input ? Output<T[Key]> :
never
};
但在访问hello
属性(如output.hello
)时,它始终是类型never