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

Commit 145a5a8

Browse files
authored
Conform more code to strict null checking (#10153)
* Conform more code to strict null checking * Conform more code to strict null checking * Iterate * Iterate
1 parent a4ff959 commit 145a5a8

File tree

89 files changed

+520
-551
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

89 files changed

+520
-551
lines changed

src/BasePlatform.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -193,7 +193,7 @@ export default abstract class BasePlatform {
193193
public displayNotification(
194194
title: string,
195195
msg: string,
196-
avatarUrl: string,
196+
avatarUrl: string | null,
197197
room: Room,
198198
ev?: MatrixEvent,
199199
): Notification {

src/Modal.tsx

Lines changed: 11 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,7 @@ export interface IModal<T extends any[]> {
3333
beforeClosePromise?: Promise<boolean>;
3434
closeReason?: string;
3535
onBeforeClose?(reason?: string): Promise<boolean>;
36-
onFinished(...args: T): void;
36+
onFinished?(...args: T): void;
3737
close(...args: T): void;
3838
hidden?: boolean;
3939
}
@@ -68,11 +68,11 @@ export class ModalManager extends TypedEventEmitter<ModalManagerEvent, HandlerMa
6868
// The modal to prioritise over all others. If this is set, only show
6969
// this modal. Remove all other modals from the stack when this modal
7070
// is closed.
71-
private priorityModal: IModal<any> = null;
71+
private priorityModal: IModal<any> | null = null;
7272
// The modal to keep open underneath other modals if possible. Useful
7373
// for cases like Settings where the modal should remain open while the
7474
// user is prompted for more information/errors.
75-
private staticModal: IModal<any> = null;
75+
private staticModal: IModal<any> | null = null;
7676
// A list of the modals we have stacked up, with the most recent at [0]
7777
// Neither the static nor priority modal will be in this list.
7878
private modals: IModal<any>[] = [];
@@ -144,17 +144,14 @@ export class ModalManager extends TypedEventEmitter<ModalManagerEvent, HandlerMa
144144
closeDialog: IHandle<T>["close"];
145145
onFinishedProm: IHandle<T>["finished"];
146146
} {
147-
const modal: IModal<T> = {
148-
onFinished: props ? props.onFinished : null,
149-
onBeforeClose: options.onBeforeClose,
150-
beforeClosePromise: null,
151-
closeReason: null,
147+
const modal = {
148+
onFinished: props?.onFinished,
149+
onBeforeClose: options?.onBeforeClose,
152150
className,
153151

154152
// these will be set below but we need an object reference to pass to getCloseFn before we can do that
155153
elem: null,
156-
close: null,
157-
};
154+
} as IModal<T>;
158155

159156
// never call this from onFinished() otherwise it will loop
160157
const [closeDialog, onFinishedProm] = this.getCloseFn<T>(modal, props);
@@ -173,7 +170,7 @@ export class ModalManager extends TypedEventEmitter<ModalManagerEvent, HandlerMa
173170

174171
private getCloseFn<T extends any[]>(
175172
modal: IModal<T>,
176-
props: IProps<T>,
173+
props?: IProps<T>,
177174
): [IHandle<T>["close"], IHandle<T>["finished"]] {
178175
const deferred = defer<T>();
179176
return [
@@ -183,13 +180,13 @@ export class ModalManager extends TypedEventEmitter<ModalManagerEvent, HandlerMa
183180
} else if (modal.onBeforeClose) {
184181
modal.beforeClosePromise = modal.onBeforeClose(modal.closeReason);
185182
const shouldClose = await modal.beforeClosePromise;
186-
modal.beforeClosePromise = null;
183+
modal.beforeClosePromise = undefined;
187184
if (!shouldClose) {
188185
return;
189186
}
190187
}
191188
deferred.resolve(args);
192-
if (props && props.onFinished) props.onFinished.apply(null, args);
189+
if (props?.onFinished) props.onFinished.apply(null, args);
193190
const i = this.modals.indexOf(modal);
194191
if (i >= 0) {
195192
this.modals.splice(i, 1);
@@ -317,7 +314,7 @@ export class ModalManager extends TypedEventEmitter<ModalManagerEvent, HandlerMa
317314
// so, pass the reason to close through a member variable
318315
modal.closeReason = "backgroundClick";
319316
modal.close();
320-
modal.closeReason = null;
317+
modal.closeReason = undefined;
321318
};
322319

323320
private getCurrentModal(): IModal<any> {

src/Notifier.ts

Lines changed: 12 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -68,7 +68,7 @@ Override both the content body and the TextForEvent handler for specific msgtype
6868
This is useful when the content body contains fallback text that would explain that the client can't handle a particular
6969
type of tile.
7070
*/
71-
const msgTypeHandlers: Record<string, (event: MatrixEvent) => string> = {
71+
const msgTypeHandlers: Record<string, (event: MatrixEvent) => string | null> = {
7272
[MsgType.KeyVerificationRequest]: (event: MatrixEvent) => {
7373
const name = (event.sender || {}).name;
7474
return _t("%(name)s is requesting verification", { name });
@@ -156,7 +156,7 @@ class NotifierClass {
156156
msg = "";
157157
}
158158

159-
let avatarUrl = null;
159+
let avatarUrl: string | null = null;
160160
if (ev.sender && !SettingsStore.getValue("lowBandwidth")) {
161161
avatarUrl = Avatar.avatarUrlForMember(ev.sender, 40, 40, "crop");
162162
}
@@ -166,8 +166,8 @@ class NotifierClass {
166166
// if displayNotification returns non-null, the platform supports
167167
// clearing notifications later, so keep track of this.
168168
if (notif) {
169-
if (this.notifsByRoom[ev.getRoomId()] === undefined) this.notifsByRoom[ev.getRoomId()] = [];
170-
this.notifsByRoom[ev.getRoomId()].push(notif);
169+
if (this.notifsByRoom[ev.getRoomId()!] === undefined) this.notifsByRoom[ev.getRoomId()!] = [];
170+
this.notifsByRoom[ev.getRoomId()!].push(notif);
171171
}
172172
}
173173

@@ -219,7 +219,7 @@ class NotifierClass {
219219
sound ? `audio[src='${sound.url}']` : "#messageAudio",
220220
);
221221
let audioElement = selector;
222-
if (!selector) {
222+
if (!audioElement) {
223223
if (!sound) {
224224
logger.error("No audio element or sound to play for notification");
225225
return;
@@ -378,11 +378,11 @@ class NotifierClass {
378378
return global.localStorage.getItem("notifications_hidden") === "true";
379379
}
380380

381-
return this.toolbarHidden;
381+
return !!this.toolbarHidden;
382382
}
383383

384384
// XXX: Exported for tests
385-
public onSyncStateChange = (state: SyncState, prevState?: SyncState, data?: ISyncStateData): void => {
385+
public onSyncStateChange = (state: SyncState, prevState: SyncState | null, data?: ISyncStateData): void => {
386386
if (state === SyncState.Syncing) {
387387
this.isSyncing = true;
388388
} else if (state === SyncState.Stopped || state === SyncState.Error) {
@@ -411,7 +411,7 @@ class NotifierClass {
411411
// If it's an encrypted event and the type is still 'm.room.encrypted',
412412
// it hasn't yet been decrypted, so wait until it is.
413413
if (ev.isBeingDecrypted() || ev.isDecryptionFailure()) {
414-
this.pendingEncryptedEventIds.push(ev.getId());
414+
this.pendingEncryptedEventIds.push(ev.getId()!);
415415
// don't let the list fill up indefinitely
416416
while (this.pendingEncryptedEventIds.length > MAX_PENDING_ENCRYPTED) {
417417
this.pendingEncryptedEventIds.shift();
@@ -427,7 +427,7 @@ class NotifierClass {
427427
// in which case it might decrypt soon if the keys arrive
428428
if (ev.isDecryptionFailure()) return;
429429

430-
const idx = this.pendingEncryptedEventIds.indexOf(ev.getId());
430+
const idx = this.pendingEncryptedEventIds.indexOf(ev.getId()!);
431431
if (idx === -1) return;
432432

433433
this.pendingEncryptedEventIds.splice(idx, 1);
@@ -456,7 +456,7 @@ class NotifierClass {
456456
public evaluateEvent(ev: MatrixEvent): void {
457457
// Mute notifications for broadcast info events
458458
if (ev.getType() === VoiceBroadcastInfoEventType) return;
459-
let roomId = ev.getRoomId();
459+
let roomId = ev.getRoomId()!;
460460
if (LegacyCallHandler.instance.getSupportsVirtualRooms()) {
461461
// Attempt to translate a virtual room to a native one
462462
const nativeRoomId = VoipUserMapper.sharedInstance().nativeRoomForVirtualRoom(roomId);
@@ -492,7 +492,7 @@ class NotifierClass {
492492
this.displayPopupNotification(ev, room);
493493
}
494494
if (actions.tweaks.sound && this.isAudioEnabled()) {
495-
PlatformPeg.get().loudNotification(ev, room);
495+
PlatformPeg.get()?.loudNotification(ev, room);
496496
this.playAudioNotification(ev, room);
497497
}
498498
}
@@ -504,7 +504,7 @@ class NotifierClass {
504504
private performCustomEventHandling(ev: MatrixEvent): void {
505505
if (ElementCall.CALL_EVENT_TYPE.names.includes(ev.getType()) && SettingsStore.getValue("feature_group_calls")) {
506506
ToastStore.sharedInstance().addOrReplaceToast({
507-
key: getIncomingCallToastKey(ev.getStateKey()),
507+
key: getIncomingCallToastKey(ev.getStateKey()!),
508508
priority: 100,
509509
component: IncomingCallToast,
510510
bodyClassName: "mx_IncomingCallToast",

src/PosthogAnalytics.ts

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -238,19 +238,19 @@ export class PosthogAnalytics {
238238
}
239239
}
240240

241-
private static async getPlatformProperties(): Promise<PlatformProperties> {
241+
private static async getPlatformProperties(): Promise<Partial<PlatformProperties>> {
242242
const platform = PlatformPeg.get();
243-
let appVersion: string;
243+
let appVersion: string | undefined;
244244
try {
245-
appVersion = await platform.getAppVersion();
245+
appVersion = await platform?.getAppVersion();
246246
} catch (e) {
247247
// this happens if no version is set i.e. in dev
248248
appVersion = "unknown";
249249
}
250250

251251
return {
252252
appVersion,
253-
appPlatform: platform.getHumanReadableName(),
253+
appPlatform: platform?.getHumanReadableName(),
254254
};
255255
}
256256

@@ -411,7 +411,7 @@ export class PosthogAnalytics {
411411
// All other scenarios should not track a user before they have given
412412
// explicit consent that they are ok with their analytics data being collected
413413
const options: IPostHogEventOptions = {};
414-
const registrationTime = parseInt(window.localStorage.getItem("mx_registration_time"), 10);
414+
const registrationTime = parseInt(window.localStorage.getItem("mx_registration_time")!, 10);
415415
if (!isNaN(registrationTime)) {
416416
options.timestamp = new Date(registrationTime);
417417
}

src/RoomInvite.tsx

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -142,7 +142,7 @@ export function showAnyInviteErrors(
142142
});
143143
return false;
144144
} else {
145-
const errorList = [];
145+
const errorList: string[] = [];
146146
for (const addr of failedUsers) {
147147
if (states[addr] === "error") {
148148
const reason = inviter.getErrorText(addr);
@@ -173,8 +173,11 @@ export function showAnyInviteErrors(
173173
<div key={addr} className="mx_InviteDialog_tile mx_InviteDialog_tile--inviterError">
174174
<div className="mx_InviteDialog_tile_avatarStack">
175175
<BaseAvatar
176-
url={avatarUrl ? mediaFromMxc(avatarUrl).getSquareThumbnailHttp(24) : null}
177-
name={name}
176+
url={
177+
(avatarUrl && mediaFromMxc(avatarUrl).getSquareThumbnailHttp(24)) ??
178+
undefined
179+
}
180+
name={name!}
178181
idName={user?.userId}
179182
width={36}
180183
height={36}

src/ScalarAuthClient.ts

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -32,8 +32,8 @@ const imApiVersion = "1.1";
3232
// TODO: Generify the name of this class and all components within - it's not just for Scalar.
3333

3434
export default class ScalarAuthClient {
35-
private scalarToken: string;
36-
private termsInteractionCallback: TermsInteractionCallback;
35+
private scalarToken: string | null;
36+
private termsInteractionCallback?: TermsInteractionCallback;
3737
private isDefaultManager: boolean;
3838

3939
public constructor(private apiUrl: string, private uiUrl: string) {
@@ -59,15 +59,15 @@ export default class ScalarAuthClient {
5959
}
6060
}
6161

62-
private readTokenFromStore(): string {
62+
private readTokenFromStore(): string | null {
6363
let token = window.localStorage.getItem("mx_scalar_token_at_" + this.apiUrl);
6464
if (!token && this.isDefaultManager) {
6565
token = window.localStorage.getItem("mx_scalar_token");
6666
}
6767
return token;
6868
}
6969

70-
private readToken(): string {
70+
private readToken(): string | null {
7171
if (this.scalarToken) return this.scalarToken;
7272
return this.readTokenFromStore();
7373
}

src/ScalarMessaging.ts

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -358,7 +358,7 @@ function inviteUser(event: MessageEvent<any>, roomId: string, userId: string): v
358358
if (room) {
359359
// if they are already invited or joined we can resolve immediately.
360360
const member = room.getMember(userId);
361-
if (member && ["join", "invite"].includes(member.membership)) {
361+
if (member && ["join", "invite"].includes(member.membership!)) {
362362
sendResponse(event, {
363363
success: true,
364364
});
@@ -389,7 +389,7 @@ function kickUser(event: MessageEvent<any>, roomId: string, userId: string): voi
389389
if (room) {
390390
// if they are already not in the room we can resolve immediately.
391391
const member = room.getMember(userId);
392-
if (!member || getEffectiveMembership(member.membership) === EffectiveMembership.Leave) {
392+
if (!member || getEffectiveMembership(member.membership!) === EffectiveMembership.Leave) {
393393
sendResponse(event, {
394394
success: true,
395395
});
@@ -472,7 +472,7 @@ function setWidget(event: MessageEvent<any>, roomId: string | null): void {
472472
} else {
473473
// Room widget
474474
if (!roomId) {
475-
sendError(event, _t("Missing roomId."), null);
475+
sendError(event, _t("Missing roomId."));
476476
return;
477477
}
478478
WidgetUtils.setRoomWidget(
@@ -675,7 +675,7 @@ function canSendEvent(event: MessageEvent<any>, roomId: string): void {
675675
sendError(event, _t("You are not in this room."));
676676
return;
677677
}
678-
const me = client.credentials.userId;
678+
const me = client.credentials.userId!;
679679

680680
let canSend = false;
681681
if (isState) {

0 commit comments

Comments
 (0)