简体   繁体   English

使用Flow和redux-navigation验证通用的React组件属性

[英]Validating generic React components properties with Flow and redux-navigation

I'm trying to validate that React components are receiving the correct properties when a new screen action is dispatched. 我正在尝试验证React组件在调度新的屏幕操作时是否正在接收正确的属性。

Routes may look like this. 路线可能如下所示。

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

An what I need is something like this. 我需要的是这样的事情。 I just have not found the way to make openScreen validate that props are good for routes[name]. 我还没有找到让openScreen验证道具对路径[名称]有用的方法。

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"});

How do I make this work? 我该如何工作?

You can use function overloading for a slightly suboptimal solutions like this: 你可以使用函数重载来获得一个稍微不理想的解决方案,如下所示:

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 {

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM