我试图在分派新的屏幕操作时验证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验证道具是否适用于路线[名称]的方法。
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"});
我如何进行这项工作?
答案 0 :(得分:0)
您可以将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 {
}