【发布时间】:2019-05-12 22:19:11
【问题描述】:
我的 react-native 应用程序中有以下(简化的)代码(我认为 react-native 无关紧要,但这是我发现错误的上下文)。
我正在尝试定义mystring 和gen 的类型以保持flow 快乐,但我找到的唯一解决方案是string|void,如下所示。下面的代码本身不会返回任何流错误,但是一旦我在其他地方使用mystring,我就会收到错误,因为应该是string,而不是void。我玩过各种组合,但没有运气。
我应该如何修改此代码以修复错误?
// @flow
import * as React from 'react';
type State = {
mystring: string|void,
};
type genType = Generator<string, void, void>;
export default class Example extends React.Component<{}, State> {
constructor(props: {}) {
super(props);
this.gen = this.makeGenerator();
const { value } = this.gen.next();
this.state = {
mystring: value,
};
}
gen: genType;
* makeGenerator(): genType {
yield 'somestring';
}
render() {
const { mystring } = this.state;
return mystring.charAt(0);
}
}
编辑:
在上面的代码上运行flow 时,最后一行(这是强制流将mystring 视为字符串的示例):
Cannot call mystring.charAt because property charAt is missing in undefined [1].
[1] 5│ mystring?: string,
【问题讨论】:
-
如何将
state定义为接口而不是类型并将mystring定义为可选?我的意思是mystring?: string。我不明白你对 void 的用法 -
this.gen.next()最后可能会返回{value: undefined, done: true},这就是void类型的来源。 (我不知道如何解决这个问题) -
@Milore 我用
void覆盖了发电机耗尽并且没有返回的情况,但是您的mystring?: string更干净。但它仍然不能解决问题,因为变量作为字符串的其他用途会引发flow错误。你能举个例子说明你所说的接口是什么意思吗? -
我通常将组件的 state 和 props 定义为
interface IState {...},但我刚刚阅读了一篇关于与您一样使用type的差异的文章,事实证明这几乎是一样的。您可以发布在其他地方使用 mystring 时遇到的确切错误吗? -
好的,我不完全理解你的问题。使用 Typescript 意味着您将处理所有变量的定义和使用中的类型,或者您正在谈论的任何内容。显然,在这种情况下,您必须面对 mystring 可能未定义的事实,并且在这种情况下您无法处理它。只需设置您的退货条件,例如
return mystring && mystring.charAt(0);
标签: javascript react-native ecmascript-6 generator flowtype