【问题标题】:Validating generic React components properties with Flow and redux-navigation使用 Flow 和 redux-navigation 验证通用 React 组件属性
【发布时间】:2018-08-09 14:14:57
【问题描述】:

我正在尝试验证 React 组件在调度新的屏幕操作时是否接收到正确的属性。

路线可能如下所示。

class MyCompAB extends React.Component<{a: number, b: string}> {}
class MyCompCD extends React.Component<{c: number, d: string}> {}
const myRoutes = {'/ab': MyCompAB, '/cd': MyCompCD};

我需要的是这样的东西。我只是还没有找到方法让 openScreen 验证 props 是否适用于路线 [name]。

type Screen<P> = ComponentType<P>;
type Routes<P> = {[key: string]: Screen<P>};

function openScreen<P, R: Routes<mixed>, K: $Keys<R>>(routes: R, name: K, props: P): void {
  // This needs to validate that props are valid for the component in routes[name].
  // This won't do <Component {...props} />. Instead redux dispatch magic happens here.
  type Pepe = $Call<R<P>, K>;
}

// $ExpectError. Should fail: a and b missing.
openScreen(myRoutes, '/ab', {});
// $ExpectError. Should fail: b has wrong type.
openScreen(myRoutes, '/ab', {a: 1, b: 1});
// Should work.
openScreen(myRoutes, '/ab', {a: 1, b: "1"});

// $ExpectError. Should fail: c and d missing.
openScreen(myRoutes, '/cd', {});
// $ExpectError. Should fail: d has wrong type.
openScreen(myRoutes, '/cd', {c: 1, d: 1});
// Should work.
openScreen(myRoutes, '/cd', {c: 1, d: "1"});

我该如何进行这项工作?

【问题讨论】:

    标签: reactjs react-native react-navigation flowtype


    【解决方案1】:

    您可以使用function overloading 来获得像这样稍微次优的解决方案:

    declare function openScreen<P: $PropertyType<MyCompAB, 'props'>, R: Routes<mixed>, K: '/ab'>(routes: R, name: K, props: P): void {
    
    }
    
    declare function openScreen<P: $PropertyType<MyCompCD, 'props'>, R: Routes<mixed>, K: '/bc'>(routes: R, name: K, props: P): void {
    
    }
    

    【讨论】:

      猜你喜欢
      • 2020-08-02
      • 2023-04-02
      • 2018-12-04
      • 1970-01-01
      • 1970-01-01
      • 2021-11-21
      • 2018-05-23
      • 2017-11-28
      • 1970-01-01
      相关资源
      最近更新 更多