【问题标题】:Typing a recursive Immutable js Record in Typescript在 Typescript 中键入递归的不可变 js 记录
【发布时间】:2021-09-03 14:32:42
【问题描述】:

我正在尝试使用不可变的 js 和打字稿来表示树状数据结构。现在,我正在使用普通的 vanilla js 对象来表示树中的节点。这是类型签名。

type NodeType = {
    value: string
    children: List<NodeType>
}

我想将其转换为记录,但我对如何执行此操作感到困惑。如果我只是为了显而易见:

const defaultValues: NodeType = {
    value: "foo",
    children: List()
}
const NodeRecord = Record(defaultValues)

...那么在顶层就可以了,但它会期望孩子的类型是NodeType而不是RecordOf(NodeType)

有人知道怎么做吗? 谢谢

【问题讨论】:

  • 您是否遇到了特殊问题?因为据我所知,您的代码可以按您的预期工作:tsplay.dev/N5EpPN

标签: typescript types typescript-generics immutable.js


【解决方案1】:

an example in the docs 可能会有所帮助。 按照您的编写方式,您的 NodeType 仅描述 默认值,而不是 Record

import type { RecordFactory, RecordOf } from 'immutable';

// Use RecordFactory<TProps> for defining new Record factory functions.
type NodeTypeProps = { 
  value: string
  children: List<RecordOf<NodeTypeProps>>
};
const defaultValues: NodeTypeProps = { value: "meh" };
const makeNodeType: RecordFactory<NodeTypeProps> = Record(defaultValues);

type NodeType = RecordOf<NodeTypeProps>;
const someNodeType: NodeType = makeNodeType({ value: "some" });

免责声明:我从未将 Immutable 与 TS 一起使用,并且知道它有时会有点痛苦。由于类型是递归的,因此可能需要额外的步骤来让 TS 编译器满意

【讨论】:

    猜你喜欢
    • 2019-04-24
    • 2020-05-06
    • 2021-12-15
    • 1970-01-01
    • 2021-08-24
    • 2018-05-23
    • 2017-10-03
    • 1970-01-01
    • 2021-05-26
    相关资源
    最近更新 更多