如何为不可变js类型写一个流类型定义

How to write a Flow Type definition for ImmutableJS Types?

本文关键字:类型 一个 定义 不可变 js      更新时间:2023-09-26

我看到ImmutableJS现在有流类型注释,但我如何定义类型?例如:

const state : ??? = Immutable.fromJS({ name: 'chet', tags: ['something']})

我可以从普通JS中定义类型,但我怎么说这是一个不可变的。有特定键的地图?

现在的问题是不可变流类型只支持每个键和值组合的一个类型定义。

所以不可变的。Maps接受Map<keyType, valueType>

和不可变的。List接受List<valueType>

Immutable.fromJS ({name:"切特",标签:['东西']})

等价于Map({name: 'chet', tags: List(['something])}

所以,你的类型定义应该是

Map<(string) | ('name', 'tags'), string | List<string>>

使用Record代替Map(或fromJS)。这并不是对代码的最佳补充,特别是如果您的状态嵌套了Record,但是类型检查支持非常好。

// @flow
import { Record, List } from 'immutable';
import type { RecordFactory, RecordOf } from 'immutable';
type StateProps = {
  name: string,
  tags: List<string>,
}
type State = RecordOf<StateProps>;
const makeState: RecordFactory<StateProps> = Record({
  name: '',
  tags: List(),
});
const state: State = makeState({
  name: 'chet',
  tags: List(['something']),
});
// Or, to to create an instance of the default
// const _state: State = makeState();

我将这种类型写成

const state: Map<string, any>

这表示state将是Map类型,Map将具有字符串键和(name, tags),值将是any。
另外,请注意,您必须执行

import type { Map } from 'immutable';

否则它会认为它是原生类型Map你会看到错误,比如Map没有get或getIn方法。

相关文章: