用于推断递归类型的打字稿提示?

时间:2021-07-18 20:58:13

标签: typescript

我正在尝试编写一个具有递归函数的库:

const generateTreeNode = () => {
  return {
    value: 1,
    // ...other properties...
    next: generateTreeNode
  };
}

如果没有任何附加信息,打字稿将无法推断递归:

declare const generateTreeNode: () => {
    value: number;
    next: any;
};

我知道如果我指定类型,我可以让编译器正确识别类型:

type TGenerateTreeNode = () => {
  value: number,
  next: TGenerateTreeNode
};

const generateTreeNode: TGenerateTreeNode = () => {
  return {
    value: 1,
    // ...other properties...
    next: generateTreeNode
  };
}

我想知道是否有任何方式向编译器提示类型定义在何处递归,而不必指定其他(非递归)属性(例如 value)。理想情况下,类似于:

type TGenerateTreeNode<TOther extends {[key: string]: any}> = () => {
  next: TGenerateTreeNode<TOther>
} & TOther;

// This errors without a defintion for the generic on TGenerateTreeNode
const generateTreeNode: TGenerateTreeNode = () => {
  return {
    value: 1,
    // ...other properties...
    next: generateTreeNode
  };
}

0 个答案:

没有答案