流向 TypeScript 迁移

Flow to TypeScript migration

我尝试将我尚未编写的项目从 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 in the playground (and the equivalent 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;
}

关于差异的一些说明:

  • 流的?ValueMaybe; TypeScript 等价物是 Value | undefined | null.
  • 流量的type可能self-reference/recurse;在 TypeScript 中 .

演示

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