Flow(+ React-Native):取决于函数参数

时间:2018-03-04 19:16:46

标签: react-native types flowtype

我想键入一个带有两个参数的函数,其中第二个参数取决于第一个参数。我的想法是为每个可能的第一个参数创建一个函数类型(在示例中为“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;

1 个答案:

答案 0 :(得分:0)

现在我最终得到了以下解决方法,但会更好地回答。

// @flow

import React, { Component } from 'react';
import { View, TouchableOpacity, Text } from 'react-native';

type NavigateOption<Screen, Params> = {
  screen: Screen,
  params: Params,
};

type NavigateOptions =
  | NavigateOption<'A', { someParam: string }>
  | NavigateOption<'B', { someOtherParam: number }>;

type Props = {
  navigation: {
    navigate: (screen: string, params?: {}) => void,
  },
};

class TestComponent extends Component<Props> {
  onPress = () => {
    this.navigate({ screen: 'A', params: { someParam: 'foo' } });
  };

  navigate = (options: NavigateOptions) => {
    this.props.navigation.navigate(options.screen, options.params);
  };

  render() {
    return (
      <TouchableOpacity onPress={this.onPress}>
        <Text>Click Me</Text>
      </TouchableOpacity>
    );
  }
}

export default TestComponent;