Skip to content

Commit bb78f12

Browse files
committed
Clean up some TypeScript problems
1 parent 826d6d2 commit bb78f12

File tree

9 files changed

+57
-67
lines changed

9 files changed

+57
-67
lines changed

node_package/src/Authenticity.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ import type { AuthenticityHeaders } from './types/index';
33
export default {
44
authenticityToken(): string | null {
55
const token = document.querySelector('meta[name="csrf-token"]');
6-
if (token && (token instanceof window.HTMLMetaElement)) {
6+
if (token instanceof HTMLMetaElement) {
77
return token.content;
88
}
99
return null;

node_package/src/ComponentRegistry.ts

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import type { RegisteredComponent, ReactComponentOrRenderFunction, RenderFunction } from './types/index';
22
import isRenderFunction from './isRenderFunction';
33

4-
const registeredComponents = new Map();
4+
const registeredComponents = new Map<string, RegisteredComponent>();
55

66
export default {
77
/**
@@ -35,8 +35,9 @@ export default {
3535
* @returns { name, component, isRenderFunction, isRenderer }
3636
*/
3737
get(name: string): RegisteredComponent {
38-
if (registeredComponents.has(name)) {
39-
return registeredComponents.get(name);
38+
const registeredComponent = registeredComponents.get(name);
39+
if (registeredComponent !== undefined) {
40+
return registeredComponent;
4041
}
4142

4243
const keys = Array.from(registeredComponents.keys()).join(', ');

node_package/src/StoreRegistry.ts

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,8 @@ import type { StoreGenerator } from './types';
33
/* eslint-disable @typescript-eslint/no-explicit-any */
44
type Store = any;
55

6-
const registeredStoreGenerators = new Map();
7-
const hydratedStores = new Map();
6+
const registeredStoreGenerators = new Map<string, StoreGenerator>();
7+
const hydratedStores = new Map<string, Store>();
88

99
export default {
1010
/**
@@ -66,8 +66,9 @@ This can happen if you are server rendering and either:
6666
* @returns storeCreator with given name
6767
*/
6868
getStoreGenerator(name: string): StoreGenerator {
69-
if (registeredStoreGenerators.has(name)) {
70-
return registeredStoreGenerators.get(name);
69+
const registeredStoreGenerator = registeredStoreGenerators.get(name);
70+
if (registeredStoreGenerator) {
71+
return registeredStoreGenerator;
7172
}
7273

7374
const storeKeys = Array.from(registeredStoreGenerators.keys()).join(', ');

node_package/src/buildConsoleReplay.ts

Lines changed: 7 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,6 @@
11
import RenderUtils from './RenderUtils';
22
import scriptSanitizedVal from './scriptSanitizedVal';
33

4-
/* eslint-disable @typescript-eslint/no-explicit-any */
5-
64
declare global {
75
interface Console {
86
history?: {
@@ -13,24 +11,25 @@ declare global {
1311

1412
export function consoleReplay(): string {
1513
// console.history is a global polyfill used in server rendering.
16-
// $FlowFixMe
1714
if (!(console.history instanceof Array)) {
1815
return '';
1916
}
2017

2118
const lines = console.history.map(msg => {
2219
const stringifiedList = msg.arguments.map(arg => {
23-
let val;
20+
let val: string | undefined;
2421
try {
25-
val = (typeof arg === 'string' || arg instanceof String) ? arg : JSON.stringify(arg);
22+
val = typeof arg === 'string' ? arg :
23+
arg instanceof String ? String(arg) :
24+
JSON.stringify(arg);
2625
if (val === undefined) {
2726
val = 'undefined';
2827
}
29-
} catch (e: any) {
30-
val = `${e.message}: ${arg}`;
28+
} catch (e) {
29+
val = `${(e as Error).message}: ${arg}`;
3130
}
3231

33-
return scriptSanitizedVal(val as string);
32+
return scriptSanitizedVal(val);
3433
});
3534

3635
return `console.${msg.level}.apply(console, ${JSON.stringify(stringifiedList)});`;

node_package/src/clientStartup.ts

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,8 +13,6 @@ import { isServerRenderHash } from './isServerRenderResult';
1313
import reactHydrateOrRender from './reactHydrateOrRender';
1414
import { supportsRootApi } from './reactApis';
1515

16-
/* eslint-disable @typescript-eslint/no-explicit-any */
17-
1816
declare global {
1917
interface Window {
2018
ReactOnRails: ReactOnRailsType;

node_package/src/handleError.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ import React from 'react';
22
import ReactDOMServer from 'react-dom/server';
33
import type { ErrorOptions } from './types/index';
44

5-
function handleRenderFunctionIssue(options: {e: Error; name?: string}): string {
5+
function handleRenderFunctionIssue(options: ErrorOptions): string {
66
const { e, name } = options;
77

88
let msg = '';

node_package/src/isRenderFunction.ts

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -8,11 +8,9 @@ import { ReactComponentOrRenderFunction, RenderFunction } from "./types/index";
88
* @param component
99
* @returns {boolean}
1010
*/
11-
export default function isRenderFunction(component: ReactComponentOrRenderFunction): boolean {
11+
export default function isRenderFunction(component: ReactComponentOrRenderFunction): component is RenderFunction {
1212
// No for es5 or es6 React Component
13-
if (
14-
(component as RenderFunction).prototype &&
15-
(component as RenderFunction).prototype.isReactComponent) {
13+
if ((component as RenderFunction).prototype?.isReactComponent) {
1614
return false;
1715
}
1816

@@ -22,7 +20,7 @@ export default function isRenderFunction(component: ReactComponentOrRenderFuncti
2220

2321
// If zero or one args, then we know that this is a regular function that will
2422
// return a React component
25-
if (component.length >= 2) {
23+
if ((component as RenderFunction).length >= 2) {
2624
return true;
2725
}
2826

node_package/src/serverRenderReactComponent.ts

Lines changed: 31 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -3,11 +3,10 @@ import type { ReactElement } from 'react';
33

44
import ComponentRegistry from './ComponentRegistry';
55
import createReactOutput from './createReactOutput';
6-
import {isServerRenderHash, isPromise} from
7-
'./isServerRenderResult';
6+
import { isPromise, isServerRenderHash } from './isServerRenderResult';
87
import buildConsoleReplay from './buildConsoleReplay';
98
import handleError from './handleError';
10-
import type { RenderParams, RenderResult, RenderingError } from './types/index';
9+
import type { RenderParams, RenderResult, RenderingError, ServerRenderResult } from './types';
1110

1211
/* eslint-disable @typescript-eslint/no-explicit-any */
1312

@@ -35,37 +34,37 @@ See https://github.com/shakacode/react_on_rails#renderer-functions`);
3534
});
3635

3736
const processServerRenderHash = () => {
38-
// We let the client side handle any redirect
39-
// Set hasErrors in case we want to throw a Rails exception
40-
hasErrors = !!(reactRenderingResult as {routeError: Error}).routeError;
41-
42-
if (hasErrors) {
43-
console.error(
44-
`React Router ERROR: ${JSON.stringify((reactRenderingResult as {routeError: Error}).routeError)}`,
45-
);
46-
}
37+
// We let the client side handle any redirect
38+
// Set hasErrors in case we want to throw a Rails exception
39+
const { redirectLocation, routeError } = reactRenderingResult as ServerRenderResult;
40+
hasErrors = !!routeError;
41+
42+
if (hasErrors) {
43+
console.error(
44+
`React Router ERROR: ${JSON.stringify(routeError)}`,
45+
);
46+
}
4747

48-
if ((reactRenderingResult as {redirectLocation: {pathname: string; search: string}}).redirectLocation) {
49-
if (trace) {
50-
const { redirectLocation } = (reactRenderingResult as {redirectLocation: {pathname: string; search: string}});
51-
const redirectPath = redirectLocation.pathname + redirectLocation.search;
52-
console.log(`\
48+
if (redirectLocation) {
49+
if (trace) {
50+
const redirectPath = redirectLocation.pathname + redirectLocation.search;
51+
console.log(`\
5352
ROUTER REDIRECT: ${name} to dom node with id: ${domNodeId}, redirect to ${redirectPath}`,
54-
);
55-
}
56-
// For redirects on server rendering, we can't stop Rails from returning the same result.
57-
// Possibly, someday, we could have the rails server redirect.
58-
return '';
53+
);
5954
}
60-
return (reactRenderingResult as { renderedHtml: string }).renderedHtml;
55+
// For redirects on server rendering, we can't stop Rails from returning the same result.
56+
// Possibly, someday, we could have the rails server redirect.
57+
return '';
58+
}
59+
return (reactRenderingResult as ServerRenderResult).renderedHtml as string;
6160
};
6261

6362
const processPromise = () => {
6463
if (!renderingReturnsPromises) {
65-
console.error('Your render function returned a Promise, which is only supported by a node renderer, not ExecJS.')
64+
console.error('Your render function returned a Promise, which is only supported by a node renderer, not ExecJS.');
6665
}
6766
return reactRenderingResult;
68-
}
67+
};
6968

7069
const processReactElement = () => {
7170
try {
@@ -105,11 +104,11 @@ as a renderFunction and not a simple React Function Component.`);
105104
message: renderError.message,
106105
stack: renderError.stack,
107106
};
108-
}
107+
};
109108

110-
if(renderingReturnsPromises) {
109+
if (renderingReturnsPromises) {
111110
const resolveRenderResult = async () => {
112-
let promiseResult;
111+
let promiseResult: RenderResult;
113112

114113
try {
115114
promiseResult = {
@@ -129,7 +128,7 @@ as a renderFunction and not a simple React Function Component.`);
129128
}),
130129
consoleReplayScript,
131130
hasErrors: true,
132-
}
131+
};
133132
renderingError = e;
134133
}
135134

@@ -143,11 +142,11 @@ as a renderFunction and not a simple React Function Component.`);
143142
return resolveRenderResult();
144143
}
145144

146-
const result = {
147-
html: renderResult,
145+
const result: RenderResult = {
146+
html: await renderResult,
148147
consoleReplayScript,
149148
hasErrors,
150-
} as RenderResult;
149+
};
151150

152151
if (renderingError) {
153152
addRenderingErrors(result, renderingError);

node_package/src/types/index.ts

Lines changed: 5 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,7 @@ interface RenderFunction {
4646
(props?: any, railsContext?: RailsContext, domNodeId?: string): RenderFunctionResult;
4747
// We allow specifying that the function is RenderFunction and not a React Function Component
4848
// by setting this property
49-
renderFunction?: boolean;
49+
renderFunction?: true;
5050
}
5151

5252
type ReactComponentOrRenderFunction = ReactComponent | RenderFunction;
@@ -87,22 +87,16 @@ export interface CreateParams extends Params {
8787
shouldHydrate?: boolean;
8888
}
8989

90-
interface FileError extends Error {
91-
fileName: string;
92-
lineNumber: string;
93-
}
94-
9590
export interface ErrorOptions {
96-
e: FileError;
91+
// fileName and lineNumber are non-standard, but useful if present
92+
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error/fileName
93+
e: Error & { fileName?: string; lineNumber?: string };
9794
name?: string;
9895
jsCode?: string;
9996
serverSide: boolean;
10097
}
10198

102-
export interface RenderingError {
103-
message: string;
104-
stack: string;
105-
}
99+
export type RenderingError = Omit<Error, 'name'>;
106100

107101
export interface RenderResult {
108102
html: string | null;

0 commit comments

Comments
 (0)