在打字稿中将嵌套对象叶键值声明为未定义 [英] Declare nested object leaf key values as undefined in typescript
问题描述
考虑如下嵌套对象
class Person {
name: string = 'name';
address: {street: string, pincode: string} = {street: 'street', pincode: '44555'};
}
有一个实用函数(undefinedAllLeadNodes) 可以取消定义所有叶节点.所以传递一个新的 Person() 在下面创建
There is a utility function(undefinedAllLeadNodes) which undefines all leaf nodes. So passing a new Person() creates below
person.name = undefined
person.address.street = undefined;
person.address.pincode = undefined;
如果我声明如下
export function undefineAllLeafProperties<
T extends object
>(obj : T) : {[key: string] : any} {
...undefine all leaf nodes here
}
它显示了 person.address.street 的编译错误,对于 {[key: string] : any}
返回类型声明听起来不错.
It shows compilation error for person.address.street and it sounds fine for {[key: string] : any}
return type declaration.
但是什么是效用函数的正确返回类型(undefinedAllLeadNodes)这样我就可以像下面一样访问它而不会出现任何错误
But What can be the proper return type for the utility function(undefinedAllLeadNodes) so that i can access it like below without any errors
person.address.street = 'update only street';
推荐答案
你可以定义这样的类型:
You may define such a type like this:
type Undefine<T extends object> = {
[K in keyof T]: T[K] extends object ? Undefine<T[K]> : T[K] | undefined
}
这里我们使用映射类型进行迭代所有键(使用 keyof 运算符)提供的 T
对象和 条件类型检查T[K]
的值是否(使用查找类型) 又是一个对象.当它是我们递归迭代 T[K]
键.否则(当 T[K]
不是对象时)我们只需更改它的类型以允许沿 T[K]
undefined 值>.
Here we're using mapped types to iterate over all keys (using keyof operator) of the provided T
object and conditional type to check whether the value of T[K]
(using lookup type) is an object again. And when it is we recursivly iterate over the T[K]
keys. Otherwise (when T[K]
is not an object) we just change it's type to allow undefined
value along the main type of T[K]
.
请记住,在 undefineAllLeafProperties
函数代码中,您可能必须键入 assert return values .因为打字稿通常无法推断条件类型,当它依赖于未指定的泛型类型参数时.
Keep in mind that inside the undefineAllLeafProperties
function code you may have to type assert return values . Because typescript generally cannot infer the exact shape of the conditional type when it depends on unspecified generic type parameter.
这篇关于在打字稿中将嵌套对象叶键值声明为未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!