typescript - 递归类型定义似乎无法处理泛型?

标签 typescript generics recursion types partial

我认为这是 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; 
}

预期行为: 我原以为第二个示例是有效的 typescript ,即 State 应该可分配给 RecursivePartial>。情况应该如此,因为假定 T 是相同类型,任何 State 都将成为它自身的一部分。

实际行为: 我收到类型错误(见上文),看来递归类型定义在遇到泛型时会中断?

TS Playground 链接 可以在这里确认代码和类型错误; ts-playground example

最佳答案

对我来说这看起来像是一个错误。解决方法:

正如我在 the Github issue 中注意到的那样,第一个也是最好的解决方法可能是打开 strictNullChecks compiler option 。我真的建议打开它并保持打开状态,因为它非常有用。


如果您不想这样做,您可以随时使用 type assertion告诉编译器您比它更了解该类型。如果编译器确实拒绝执行断言,您可以通过 any 的断言传递它。 ,像这样:

function create_2<T>(){
    let x: RecursivePartial<State<T>>;
    let y: State<T>;
    x = y as any as RecursivePartial<State<T>>; // I know it!
}

如果您不想这样做,您可以更改 RecursivePartial<> 的定义到以下内容:

type RecursivePartial<T> = {
    [P in keyof T]?: T[P] | RecursivePartial<T[P]>;
};

我相信,这实际上是同一件事,但编译器可以更轻松地看到您始终可以分配 T 类型的值。到 RecursivePartial<T> 类型的变量.


希望有帮助。祝你好运!

关于typescript - 递归类型定义似乎无法处理泛型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45689373/

相关文章:

interface - 如何转换为对象可能实现的接口(interface)?

java - 泛型中原始类型和 <?> 的区别

javascript - TypeScript 中类型参数的可选计数

javascript - 如何将图像传递给函数 Ionic 2

spring-mvc - 如何将通用集合类对象作为参数传递

c# - 协变、委托(delegate)和泛型类型约束

python - 欧拉计划 78 - 硬币分区

c++ - 如果结构作为递归函数中的参数传递,我如何初始化结构的成员变量?

for-loop - GO - 递归函数中的 switch 语句

javascript - Mocha : Is there a scenario where a before hook would run after a test?