【发布时间】:2018-01-23 04:03:30
【问题描述】:
我认为这是 Typescript 中的一个错误,我将其提交为问题 here。我不希望它被修复(至少不会很快,所以我想问你们,有没有人碰巧有一个比 create_1 更好的解决方案/解决方法的想法?
代码
type RecursivePartial<T> = {
[P in keyof T]?: RecursivePartial<T[P]>;
};
type State<T> = { value: T };
function create_1<T>(){
let _x: RecursivePartial<State<T>>;
let _y: State<RecursivePartial<T>>;
_x = _y;
}
function create_2<T>(){
/*
*/
let x: RecursivePartial<State<T>>;
let y: State<T>;
/*
Type 'State<T>' is not assignable to type RecursivePartial<State<T>>'.
Types of property 'value' are incompatible.
Type 'T' is not assignable to type RecursivePartial<T>[P]>'.
Type 'T[string]' is not assignable to type 'RecursivePartial<T[P]>'.
*/
x = y;
}
预期行为: 我曾期望第二个示例是有效的打字稿,即 State 应该可以分配给 RecursivePartial>。应该是这种情况,因为任何状态都将是它自身的一部分,因为 T 是相同的类型。
实际行为: 我得到一个类型错误(见上文),似乎递归类型定义在遇到泛型时会中断?
TS Playground 链接 代码和类型错误可以在这里确认; ts-playground example
【问题讨论】:
-
作为信息:基于当前版本 2.4 的文档,类型别名不允许使用 Recusive Types typescriptlang.org/docs/handbook/advanced-types.html "但是,类型别名不可能出现在右侧的其他任何地方声明……”
-
@Magu,我认为这与这里无关;递归类型只在属性中提及自己,这是允许的。 (类型编译没有错误的事实表明它很好)。这里的怪异与类型检查有关。
-
@tugend,我在使用的 2.5.0-dev.20170627 版本的打字稿上没有看到这个错误。也许它是固定的?目前无法追踪它
-
使用 typescript@rc 时问题仍然存在。我应该尝试与 RC 不同的版本吗?如何获得?我在“github.com/Microsoft/TypeScript”上找不到任何类似的标签。
-
感谢您在此跟进。
标签: typescript generics recursion types partial