如何检查提供给 React 组件的 属性 是否是 Immutable.js Record with Flow 的实例?
How to check whether a property supplied to React component is an instance of Immutable.js Record with Flow?
尝试在我的项目中设置 Flow,但不太了解如何使用不可变记录。我想静态检查组件道具,我是这样做的:
// @flow
import React from "react";
import {render} from "react-dom";
import * as I from "immutable";
const Person = I.Record({
name: null,
});
type Props = {
data: Person,
};
const PersonInfo = (props: Props) => {
const {data} = props;
return (
<span>
Name: {data.name}
</span>
);
};
render(
<PersonInfo data={1} />, // I would expect to get some compile error here
document.getElementById("app")
);
我还在项目中添加了immutable.js.flow
和.flowconfig
。
这实际上是 Immutable.js 类型定义的问题。它总是 returns 和 any
type. Basically meaning Record
s aren't typechecked. I went into the reason why records are so loosly defined . The gist of it is, Flow doesn't support intersect-types with objects yet (which the type of a record would have to be). But you can override the Record
type with the more restrictive type definition describedd in 。 我复制过来了:
declare class Record<T: Object> {
static <T: Object>(spec: T, name?: string): Record<T>;
get: <A>(key: $Keys<T>) => A;
set<A>(key: $Keys<T>, value: A): Record<T>;
remove(key: $Keys<T>): Record<T>;
}
如果您将此 decleration 添加为本地 decleration,您将无法再直接访问属性(就像您使用 data.name
所做的那样),但必须使用 get
像这样的函数 data.get('name')
。与添加的类型保存相比,IMO 这个定义的缺点非常小。遗憾的是,由于语言中的其他限制,值的类型未进行类型检查,如 illustrated in this example.
可悲的是,在 Flow 中还没有针对强类型不可变数据结构的好的解决方案。不过,实现这一完美所需的功能几乎都在 Flow 的路线图上。
TL;DR
由于语言限制,Record
未进行类型检查。但是您可以使用上面提供的声明来改进类型检查。
尝试在我的项目中设置 Flow,但不太了解如何使用不可变记录。我想静态检查组件道具,我是这样做的:
// @flow
import React from "react";
import {render} from "react-dom";
import * as I from "immutable";
const Person = I.Record({
name: null,
});
type Props = {
data: Person,
};
const PersonInfo = (props: Props) => {
const {data} = props;
return (
<span>
Name: {data.name}
</span>
);
};
render(
<PersonInfo data={1} />, // I would expect to get some compile error here
document.getElementById("app")
);
我还在项目中添加了immutable.js.flow
和.flowconfig
。
这实际上是 Immutable.js 类型定义的问题。它总是 returns 和 any
type. Basically meaning Record
s aren't typechecked. I went into the reason why records are so loosly defined Record
type with the more restrictive type definition describedd in
declare class Record<T: Object> {
static <T: Object>(spec: T, name?: string): Record<T>;
get: <A>(key: $Keys<T>) => A;
set<A>(key: $Keys<T>, value: A): Record<T>;
remove(key: $Keys<T>): Record<T>;
}
如果您将此 decleration 添加为本地 decleration,您将无法再直接访问属性(就像您使用 data.name
所做的那样),但必须使用 get
像这样的函数 data.get('name')
。与添加的类型保存相比,IMO 这个定义的缺点非常小。遗憾的是,由于语言中的其他限制,值的类型未进行类型检查,如 illustrated in this example.
可悲的是,在 Flow 中还没有针对强类型不可变数据结构的好的解决方案。不过,实现这一完美所需的功能几乎都在 Flow 的路线图上。
TL;DR
由于语言限制,Record
未进行类型检查。但是您可以使用上面提供的声明来改进类型检查。