是否有一种方法可以确保在为已知类型分配any
值时在流中生成错误?
// @flow strict
type MyType = {|
propA: string
|};
const x: MyType = {
propA: "Hello, Stackoverflow!" // Works.
};
const y: MyType = {
propA: x[0] // Works, but I don't want it to.
};
const z: MyType = {
propA: window.propDoesNotExist // Works, but I don't want it to.
};
.flowconfig
...
[strict]
nonstrict-import
unclear-type
unsafe-getters-setters
untyped-import
untyped-type-import
我想使propA
更加严格,以便只允许已知的string
值。
答案 0 :(得分:1)
您可以定义键的类型和对象的值:
Flow documentation: Object as maps
如果您需要严格的密钥:
type Enum = 'propA' | 'propB';
type MyType = {
[Enum]: string
};
如果您不需要严格的密钥:
type MyType = {
[string]: string
};
文档引用:
出于文档目的,可以选择命名索引器:
type MyType = {
[propA: string]: string
};
编辑:任何用法都会触发错误=> strict mode