【发布时间】:2018-03-14 20:07:15
【问题描述】:
我想键入一个带有两个参数的函数,其中第二个参数取决于第一个参数。我的想法是为每个可能的第一个参数(例如“A”和“B”)创建一个函数类型,并将它们与“|”组合成另一种类型(或)条件,但当我尝试使用第一个参数的一个可能值调用函数时,这会导致错误“字符串(预期的字符串文字B,得到A 而不是字符串文字B)”。
// @flow
import React, { Component } from 'react';
import { View, TouchableOpacity, Text } from 'react-native';
type GoToScreenA = (screen: 'A', params: { someParam: string }) => void;
type GoToScreenB = (screen: 'B', params: { someOtherParam: number }) => void;
type GoToScreen = GoToScreenA | GoToScreenB;
type Props = {
navigation: {
navigate: GoToScreen,
},
};
class TestComponent extends Component<Props> {
onPress = () => {
this.props.navigation.navigate('A', { someParam: 'foo' });
// flow throws: string (Expected string literal `B`, got `A` instead string literal `B`)
};
render() {
return (
<TouchableOpacity onPress={this.onPress}>
<Text>Click Me</Text>
</TouchableOpacity>
);
}
}
export default TestComponent;
【问题讨论】:
标签: react-native types flowtype