如果给定的字段是在另一个对象中指定的,有没有办法递归地省略对象中的字段?
我想指定我希望从API调用中接收哪些字段,然后让输入脚本正确地输入它(删除API调用中从未指定的字段).
interface Person {
head: {
hairColor: string
eyeColor: string
}
}
const person: Person = {
head: {
hairColor: 'gray',
eyeColor: 'green',
}
}
// Converts all values in an object to boolean (recursively)
type BooleanValues<T> = {
[K in keyof T]?: T[K] extends object ? BooleanValues<T[K]> : boolean
}
const fieldsToInclude: BooleanValues<Person> = {
head: {
hairColor: true,
// No need to specify 'false' values. Unspecified fields should default to 'false' and be omitted.
}
}
dropFields(person, fieldsToInclude)
function dropFields<T>(x: T, y: BooleanValues<T>): IncludeFieldsBasedOn<T, typeof y> {
return // ...
}
你怎么打IncludeFieldsBasedOn<T, U>
这个字?
我试过了,但由于输入错误,无法正常工作:
type IncludeFieldsBasedOn<T, O extends BooleanValues<T>> = {
[K in keyof T]: T[K] extends object ? IncludeFieldsBasedOn<T[K], O[K]> : O[K] extends true ? T[K] : never
}
上面的问题是,它不理解O[K]
将与T
类型中的值"匹配".