You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

递归约束默认值导致缺省第一个参数时第二个参数类型推断错误

TypeScript递归二叉搜索树泛型约束的类型推断问题

我正在用TypeScript的泛型约束建模递归二叉搜索树(BST)数据类型。由于递归泛型变量<T>的默认值中不允许直接使用<T>,我为约束设置了互递归的“基础情况”,代码如下:

// Bounded polymorphism using recursive generic constraints.
type IBSTBoRecDflt<K, V> = IBSTBoRec<K, V, IBSTBoRecDflt<K, V>>;

interface IBSTBoRec<K, V, T extends IBSTBoRec<K, V, T> = IBSTBoRecDflt<K, V>> {
    key: K;
    value: V;
    left?: T;
    right?: T;
}

type BSTBoRecDeflt<K, V> = BSTBoRec<K, V, BSTBoRecDeflt<K, V>>;

class BSTBoRec<K, V, T extends BSTBoRec<K, V, T> = BSTBoRecDeflt<K, V>> implements IBSTBoRec<K, V, T> {
    key: K;
    value: V;
    left?: T;
    right?: T;

    constructor(key: K, value: V, left?: T, right?: T) { 
        this.key = key;
        this.value = value;
        this.left = left;
        this.right = right;    
    }
}

const t = new BSTBoRec(5, 'e', undefined, new BSTBoRec(8, 'h'));

问题在于,当左分支缺省时,右分支new BSTBoRec(8, 'h')的类型推断不正确,抛出如下错误:

Argument of type 'BSTBoRec<number, string, BSTBoRec<number, string, undefined>>' is not assignable to parameter of type 
                 'BSTBoRec<number, string, BSTBoRec<number, string, BSTBoRec<number, string, undefined>>>'.
  Type 'BSTBoRec<number, string, undefined>' is not assignable to type 
       'BSTBoRec<number, string, BSTBoRec<number, string, undefined>>'.
    Type 'undefined' is not assignable to type 'BSTBoRec<number, string, undefined>'.

如果手动指定该右分支的<K, V>类型,错误就会消失:

const t = new BSTBoRec(5, 'e', undefined, new BSTBoRec<number, string>(8, 'h'));

为什么左分支被省略时,右分支的类型会被错误推断?


内容的提问来源于stack exchange,提问作者Robert Kajic

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.23 22:25:04