我尝试将尚未编写的项目从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 itself
和Type alias 'Value' circularly references itself
。我了解此错误的含义,但我找不到在TS中没有错误的情况下获得相同行为的方法。
有什么主意吗?
答案 0 :(得分:2)
这里是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;
}
有关差异的一些说明:
?Value
是Maybe
; TypeScript等效为Value | undefined | null
。type
可以自引用/递归;在TypeScript an interface may self-reference/recurse but a type usually may not中。演示
const x: BaseObject = {
prop1: null,
prop2: undefined,
prop3: 'prop3',
prop4: 10,
prop5: {
meta: {}
},
prop6: [{
meta: {}
}],
prop7: new Date() // causes an error
}