Skip to content
This repository has been archived by the owner on Sep 11, 2024. It is now read-only.

Commit

Permalink
Conform more of the codebase to strictNullChecks (#11134)
Browse files Browse the repository at this point in the history
  • Loading branch information
t3chguy committed Jun 27, 2023
1 parent 3d886de commit e1cad41
Show file tree
Hide file tree
Showing 15 changed files with 44 additions and 36 deletions.
8 changes: 3 additions & 5 deletions src/MatrixClientPeg.ts
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ export interface IMatrixClientPeg {
*
* @returns {string} The homeserver name, if present.
*/
getHomeserverName(): string | null;
getHomeserverName(): string;

get(): MatrixClient | null;
safeGet(): MatrixClient;
Expand Down Expand Up @@ -358,10 +358,8 @@ class MatrixClientPegClass implements IMatrixClientPeg {
};
}

public getHomeserverName(): string | null {
if (!this.matrixClient) return null;

const matches = /^@[^:]+:(.+)$/.exec(this.matrixClient.getSafeUserId());
public getHomeserverName(): string {
const matches = /^@[^:]+:(.+)$/.exec(this.safeGet().getSafeUserId());
if (matches === null || matches.length < 1) {
throw new Error("Failed to derive homeserver name from user ID!");
}
Expand Down
10 changes: 6 additions & 4 deletions src/Searching.ts
Original file line number Diff line number Diff line change
Expand Up @@ -234,9 +234,11 @@ async function localPagination(
): Promise<ISeshatSearchResults> {
const eventIndex = EventIndexPeg.get();

const searchArgs = searchResult.seshatQuery;
if (!searchResult.seshatQuery) {
throw new Error("localSearchProcess must be called first");
}

const localResult = await eventIndex!.search(searchArgs);
const localResult = await eventIndex!.search(searchResult.seshatQuery);
if (!localResult) {
throw new Error("Local search pagination failed");
}
Expand Down Expand Up @@ -408,7 +410,7 @@ function combineEvents(
): IResultRoomEvents {
const response = {} as IResultRoomEvents;

const cachedEvents = previousSearchResult.cachedEvents;
const cachedEvents = previousSearchResult.cachedEvents ?? [];
let oldestEventFrom = previousSearchResult.oldestEventFrom;
response.highlights = previousSearchResult.highlights;

Expand Down Expand Up @@ -564,7 +566,7 @@ async function combinedPagination(
// Fetch events from the server if we have a token for it and if it's the
// local indexes turn or the local index has exhausted its results.
if (searchResult.serverSideNextBatch && (oldestEventFrom === "local" || !searchArgs.next_batch)) {
const body = { body: searchResult._query, next_batch: searchResult.serverSideNextBatch };
const body = { body: searchResult._query!, next_batch: searchResult.serverSideNextBatch };
serverSideResult = await client.search(body);
}

Expand Down
2 changes: 1 addition & 1 deletion src/components/structures/RoomView.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -1704,7 +1704,7 @@ export class RoomView extends React.Component<IRoomProps, IRoomState> {
} catch (error) {
logger.error(`Failed to reject invite: ${error}`);

const msg = error.message ? error.message : JSON.stringify(error);
const msg = error instanceof Error ? error.message : JSON.stringify(error);
Modal.createDialog(ErrorDialog, {
title: _t("Failed to reject invite"),
description: msg,
Expand Down
2 changes: 1 addition & 1 deletion src/components/structures/ScrollPanel.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -700,7 +700,7 @@ export default class ScrollPanel extends React.Component<IProps> {
const trackedNode = this.getTrackedNode();
if (trackedNode) {
const newBottomOffset = this.topFromBottom(trackedNode);
const bottomDiff = newBottomOffset - scrollState.bottomOffset;
const bottomDiff = newBottomOffset - (scrollState.bottomOffset ?? 0);
this.bottomGrowth += bottomDiff;
scrollState.bottomOffset = newBottomOffset;
const newHeight = `${this.getListHeight()}px`;
Expand Down
12 changes: 8 additions & 4 deletions src/components/structures/TimelinePanel.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -599,7 +599,7 @@ class TimelinePanel extends React.Component<IProps, IState> {

if (!this.timelineWindow?.canPaginate(dir)) {
debuglog("can't", dir, "paginate any further");
this.setState<null>({ [canPaginateKey]: false });
this.setState({ [canPaginateKey]: false } as Pick<IState, typeof canPaginateKey>);
return Promise.resolve(false);
}

Expand All @@ -609,7 +609,7 @@ class TimelinePanel extends React.Component<IProps, IState> {
}

debuglog("Initiating paginate; backwards:" + backwards);
this.setState<null>({ [paginatingKey]: true });
this.setState({ [paginatingKey]: true } as Pick<IState, typeof paginatingKey>);

return this.onPaginationRequest(this.timelineWindow, dir, PAGINATE_SIZE).then(async (r) => {
if (this.unmounted) {
Expand Down Expand Up @@ -2012,7 +2012,7 @@ class TimelinePanel extends React.Component<IProps, IState> {
return receiptStore?.getEventReadUpTo(myUserId, ignoreSynthesized) ?? null;
}

private setReadMarker(eventId: string | null, eventTs: number, inhibitSetState = false): void {
private setReadMarker(eventId: string | null, eventTs?: number, inhibitSetState = false): void {
const roomId = this.props.timelineSet.room?.roomId;

// don't update the state (and cause a re-render) if there is
Expand All @@ -2023,7 +2023,11 @@ class TimelinePanel extends React.Component<IProps, IState> {

// in order to later figure out if the read marker is
// above or below the visible timeline, we stash the timestamp.
TimelinePanel.roomReadMarkerTsMap[roomId ?? ""] = eventTs;
if (eventTs !== undefined) {
TimelinePanel.roomReadMarkerTsMap[roomId ?? ""] = eventTs;
} else {
delete TimelinePanel.roomReadMarkerTsMap[roomId ?? ""];
}

if (inhibitSetState) {
return;
Expand Down
4 changes: 2 additions & 2 deletions src/components/views/messages/MjolnirBody.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -18,15 +18,15 @@ import React from "react";
import { MatrixEvent } from "matrix-js-sdk/src/models/event";

import { _t } from "../../../languageHandler";
import AccessibleButton from "../elements/AccessibleButton";
import AccessibleButton, { ButtonEvent } from "../elements/AccessibleButton";

interface IProps {
mxEvent: MatrixEvent;
onMessageAllowed: () => void;
}

export default class MjolnirBody extends React.Component<IProps> {
private onAllowClick = (e: React.MouseEvent): void => {
private onAllowClick = (e: ButtonEvent): void => {
e.preventDefault();
e.stopPropagation();

Expand Down
2 changes: 1 addition & 1 deletion src/components/views/rooms/RoomListHeader.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -171,7 +171,7 @@ const RoomListHeader: React.FC<IProps> = ({ onVisibilityChange }) => {
contextMenu = (
<ContextMenuComponent
{...contextMenuBelow(mainMenuHandle.current.getBoundingClientRect())}
space={activeSpace}
space={activeSpace!}
onFinished={closeMainMenu}
hideHeader={true}
/>
Expand Down
2 changes: 1 addition & 1 deletion src/components/views/rooms/RoomPreviewBar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -155,7 +155,7 @@ export default class RoomPreviewBar extends React.Component<IProps, IState> {
);
this.setState({ invitedEmailMxid: result.mxid });
} catch (err) {
this.setState({ threePidFetchError: err });
this.setState({ threePidFetchError: err as MatrixError });
}
this.setState({ busy: false });
}
Expand Down
6 changes: 1 addition & 5 deletions src/stores/ModalWidgetStore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -70,11 +70,7 @@ export class ModalWidgetStore extends AsyncStoreWithClient<IState> {
widgetRoomId,
sourceWidgetId: sourceWidget.id,
onFinished: (success, data) => {
if (!success) {
this.closeModalWidget(sourceWidget, widgetRoomId, { "m.exited": true });
} else {
this.closeModalWidget(sourceWidget, widgetRoomId, data);
}
this.closeModalWidget(sourceWidget, widgetRoomId, success && data ? data : { "m.exited": true });

this.openSourceWidgetId = null;
this.openSourceWidgetRoomId = null;
Expand Down
4 changes: 2 additions & 2 deletions src/stores/right-panel/RightPanelStore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -363,15 +363,15 @@ export default class RightPanelStore extends ReadyWatchingStore {
const panel = this.byRoom[this.viewedRoomId];
if (panel?.history) {
panel.history = panel.history.filter(
(card) =>
(card: IRightPanelCard) =>
card.phase != RightPanelPhases.RoomMemberInfo &&
card.phase != RightPanelPhases.Room3pidMemberInfo,
);
}
}
// when we're switching to a room, clear out thread permalinks to not get you stuck in the middle of the thread
// in order to fix https://github.com/matrix-org/matrix-react-sdk/pull/11011
if (this.currentCard?.phase === RightPanelPhases.ThreadView) {
if (this.currentCard?.phase === RightPanelPhases.ThreadView && this.currentCard.state) {
this.currentCard.state.initialEvent = undefined;
this.currentCard.state.isInitialEventHighlighted = undefined;
this.currentCard.state.initialEventScrollIntoView = undefined;
Expand Down
10 changes: 9 additions & 1 deletion src/utils/AutoDiscoveryUtils.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -261,7 +261,15 @@ export default class AutoDiscoveryUtils {
throw new UserFriendlyError("Unexpected error resolving homeserver configuration");
}

let delegatedAuthentication = undefined;
let delegatedAuthentication:
| {
authorizationEndpoint: string;
registrationEndpoint?: string;
tokenEndpoint: string;
account?: string;
issuer: string;
}
| undefined;
if (discoveryResult[M_AUTHENTICATION.stable!]?.state === AutoDiscovery.SUCCESS) {
const { authorizationEndpoint, registrationEndpoint, tokenEndpoint, account, issuer } = discoveryResult[
M_AUTHENTICATION.stable!
Expand Down
4 changes: 2 additions & 2 deletions src/utils/DecryptFile.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ export async function decryptFile(file?: IEncryptedFile, info?: IMediaEventInfo)
}
responseData = await response.arrayBuffer();
} catch (e) {
throw new DownloadError(e);
throw new DownloadError(e as Error);
}

try {
Expand All @@ -77,6 +77,6 @@ export async function decryptFile(file?: IEncryptedFile, info?: IMediaEventInfo)

return new Blob([dataArray], { type: mimetype });
} catch (e) {
throw new DecryptError(e);
throw new DecryptError(e as Error);
}
}
2 changes: 1 addition & 1 deletion src/utils/StorageManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ function log(msg: string): void {
logger.log(`StorageManager: ${msg}`);
}

function error(msg: string, ...args: string[]): void {
function error(msg: string, ...args: any[]): void {
logger.error(`StorageManager: ${msg}`, ...args);
}

Expand Down
4 changes: 2 additions & 2 deletions src/utils/promise.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,14 +33,14 @@ export async function retry<T, E extends Error>(
num: number,
predicate?: (e: E) => boolean,
): Promise<T> {
let lastErr!: E;
let lastErr!: any;
for (let i = 0; i < num; i++) {
try {
const v = await fn();
// If `await fn()` throws then we won't reach here
return v;
} catch (err) {
if (predicate && !predicate(err)) {
if (predicate && !predicate(err as E)) {
throw err;
}
lastErr = err;
Expand Down
8 changes: 4 additions & 4 deletions test/utils/media/requestMediaPermissions-test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ describe("requestMediaPermissions", () => {
describe("when an audio and video device is available", () => {
beforeEach(() => {
mocked(navigator.mediaDevices.getUserMedia).mockImplementation(
async ({ audio, video }): Promise<MediaStream> => {
async ({ audio, video }: MediaStreamConstraints): Promise<MediaStream> => {
if (audio && video) return audioVideoStream;
return audioStream;
},
Expand All @@ -56,7 +56,7 @@ describe("requestMediaPermissions", () => {
describe("when calling with video = false and an audio device is available", () => {
beforeEach(() => {
mocked(navigator.mediaDevices.getUserMedia).mockImplementation(
async ({ audio, video }): Promise<MediaStream> => {
async ({ audio, video }: MediaStreamConstraints): Promise<MediaStream> => {
if (audio && !video) return audioStream;
return audioVideoStream;
},
Expand All @@ -72,7 +72,7 @@ describe("requestMediaPermissions", () => {
beforeEach(() => {
error.name = "NotFoundError";
mocked(navigator.mediaDevices.getUserMedia).mockImplementation(
async ({ audio, video }): Promise<MediaStream> => {
async ({ audio, video }: MediaStreamConstraints): Promise<MediaStream> => {
if (audio && video) throw error;
if (audio) return audioStream;
return audioVideoStream;
Expand Down Expand Up @@ -103,7 +103,7 @@ describe("requestMediaPermissions", () => {
describe("when an Error is raised", () => {
beforeEach(async () => {
mocked(navigator.mediaDevices.getUserMedia).mockImplementation(
async ({ audio, video }): Promise<MediaStream> => {
async ({ audio, video }: MediaStreamConstraints): Promise<MediaStream> => {
if (audio && video) throw error;
return audioVideoStream;
},
Expand Down

0 comments on commit e1cad41

Please sign in to comment.