【发布时间】:2017-05-25 14:54:31
【问题描述】:
我有一个满足以下条件的函数:
1) 它使用一个对象,可以有任何级别的嵌套,比如 Redux 的 State。在嵌套结束时,它有一些类实例,我们称之为Leaf。因此,示例对象类型可能如下所示:
type Sample = {
nested1: {
nested2: Leaf,
},
nonesting: Leaf
}
或者,它可能看起来像这样:
type Sample2 = {
nested1: {
nested2: {
nested3: {
nested4: Leaf
}
},
nested5: {
nested6: {
nested7: Leaf
}
}
},
nested8: {
nested9: Leaf
}
}
就像 Redux 的 State 一样,没关系。这取决于图书馆用户。
2) 它返回一个与输入对象具有完全相同结构的对象,但该对象中的所有Leaf 都被替换为ProcessedLeaf。
我希望能够访问该对象的ProcessedLeaf,如下所示:
result.nested1.nested2
当前状态
这是我探索的结果:
interface InputObject {
[key: string]: InputObject | Leaf
}
interface OutputObject {
[key: string]: OutputObject | ProcessedLeaf
}
function process(input: InputObject): OutputObject;
但是,当我尝试使用点符号访问对象时,出现错误:
TS2339:Property 'nested2' does not exist on type 'ProcessedLeaf | OutputObject'.
Property 'nested2' does not exist on type 'ProcessedLeaf'.
另一个尝试:
interface InputObject {
[key: string]: InputObject | Leaf
}
type OutputObject<T> = {
[key in keyof T]: OutputObject<T[key]> | ProcessedLeaf
}
function process<T extends InputObject>(input: T): OutputObject<T>;
但是,错误类似:
TS2339:Property 'nested2' does not exist on type 'ProcessedLeaf | OutputObject<{ nested2: Leaf; }>'.
Property 'nested2' does not exist on type 'ProcessedLeaf'.
我知道有一种方法可以通过以下方式调用元素:
result['nested1']['nested2']
但它没有任何利润。我可以从函数中返回any,它会是一样的。
是否可以使用当前的打字稿创建这种类型?
【问题讨论】:
-
可能要等到this issue才能解决。
-
@kimamula,是的,这正是我一直在寻找的。你能把它写成答案吗?
标签: typescript