【问题标题】:Flow to TypeScript migration流向 TypeScript 迁移
【发布时间】:2019-07-07 19:35:18
【问题描述】:

我尝试将尚未编写的项目从 Flow 迁移到 TypeScript。 我有一些 Flow 结构,我在 TypeScript 中找不到对应的结构。

type Value =
  | string
  | number
  | boolean
  | BaseObject
  | Array<BaseObject>

type BaseObject = ObjectMap<?Value> & {
  meta?: BaseObject;
}

type ObjectMap<T> = {
  [key: string]: T;
};

我收到此错误:Type alias 'BaseObject' circularly references itselfType alias 'Value' circularly references itself。我理解这个错误的含义,但我找不到在 TS 中没有错误的情况下获得相同行为的方法。

有什么想法吗?

【问题讨论】:

  • 能否请您发布您尝试复制的流程结构。
  • 你是什么意思?我发布了导致错误的代码。
  • 是 TypeScript 代码、Flow 代码还是两者兼而有之?查看您尝试复制的 Flow 代码以及您尝试的 TypeScript 代码会很有帮助。
  • 这是流程代码。我只是试着让它用 tsc 编译。
  • 嗯,是的,对不起。我已经改编了一部分。我用原始代码更新我的问题

标签: typescript flowtype


【解决方案1】:

这是TypeScript in the playground(和等效的Flow in the playground)。

// The unchanged Flow type works in TypeScript.
type Value =
    | string
    | number
    | boolean
    | BaseObject
    | Array<BaseObject>

// The unchanged Flow type works in TypeScript.
type ObjectMap<T> = {
    [key: string]: T;
};

// The unchanged Flow type...
// type BaseObject = ObjectMap<?Value> & {
//     meta?: BaseObject;
// }

// ...and the equivalent TypeScript.
interface BaseObject extends ObjectMap<Value | null | undefined> {
    meta?: BaseObject;
}

关于差异的一些说明:

演示

const x: BaseObject = {
    prop1: null,
    prop2: undefined,
    prop3: 'prop3',
    prop4: 10,
    prop5: {
        meta: {}
    },
    prop6: [{
        meta: {}
    }],
    prop7: new Date() // causes an error
}

【讨论】:

  • 轻微改进:将ObjectMap&lt;Value&gt; 替换为Record&lt;string, Value&gt;。无需为此引入额外的类型。
猜你喜欢
  • 2022-01-12
  • 2016-02-26
  • 1970-01-01
  • 1970-01-01
  • 2011-06-01
  • 2017-11-03
  • 2021-12-15
  • 2017-01-09
  • 1970-01-01
相关资源
最近更新 更多