Improve typescript null checking in places (#10073 (#10073

* Improve typescript null checking in places

* Iterate

* Fix Timer.ts
This commit is contained in:
Michael Telatynski 2023-02-03 15:27:47 +00:00 committed by GitHub
parent 97506cbcdb
commit 9743852380
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
43 changed files with 155 additions and 154 deletions

View file

@ -62,7 +62,7 @@ export class DialogOpener {
roomId: payload.room_id || SdkContextClass.instance.roomViewStore.getRoomId(),
initialTabId: payload.initial_tab_id,
},
/*className=*/ null,
/*className=*/ undefined,
/*isPriority=*/ false,
/*isStatic=*/ true,
);
@ -90,7 +90,7 @@ export class DialogOpener {
initialTabId: payload.initalTabId,
space: payload.space,
},
null,
undefined,
false,
true,
);
@ -102,7 +102,7 @@ export class DialogOpener {
matrixClient: payload.space.client,
space: payload.space,
},
/*className=*/ null,
/*className=*/ undefined,
/*isPriority=*/ false,
/*isStatic=*/ true,
);

View file

@ -62,9 +62,9 @@ export async function upgradeRoom(
progressCallback?: (progress: IProgress) => void,
): Promise<string> {
const cli = room.client;
let spinnerModal: IHandle<any>;
let spinnerModal: IHandle<any> | undefined;
if (!progressCallback) {
spinnerModal = Modal.createDialog(Spinner, null, "mx_Dialog_spinner");
spinnerModal = Modal.createDialog(Spinner, undefined, "mx_Dialog_spinner");
}
let toInvite: string[] = [];
@ -78,7 +78,9 @@ export async function upgradeRoom(
if (updateSpaces) {
parentsToRelink = Array.from(SpaceStore.instance.getKnownParents(room.roomId))
.map((roomId) => cli.getRoom(roomId))
.filter((parent) => parent?.currentState.maySendStateEvent(EventType.SpaceChild, cli.getUserId()));
.filter((parent) =>
parent?.currentState.maySendStateEvent(EventType.SpaceChild, cli.getUserId()!),
) as Room[];
}
const progress: IProgress = {
@ -117,7 +119,7 @@ export async function upgradeRoom(
if (toInvite.length > 0) {
// Errors are handled internally to this function
await inviteUsersToRoom(newRoomId, toInvite, false, () => {
progress.inviteUsersProgress++;
progress.inviteUsersProgress!++;
progressCallback?.(progress);
});
}
@ -137,7 +139,7 @@ export async function upgradeRoom(
);
await cli.sendStateEvent(parent.roomId, EventType.SpaceChild, {}, room.roomId);
progress.updateSpacesProgress++;
progress.updateSpacesProgress!++;
progressCallback?.(progress);
}
} catch (e) {

View file

@ -51,7 +51,7 @@ export async function shieldStatusForRoom(client: MatrixClient, room: Room): Pro
!inDMMap && // Don't alarm for self in DMs with other users
members.length !== 2) || // Don't alarm for self in 1:1 chats with other users
members.length === 1; // Do alarm for self if we're alone in a room
const targets = includeUser ? [...verified, client.getUserId()] : verified;
const targets = includeUser ? [...verified, client.getUserId()!] : verified;
for (const userId of targets) {
const devices = client.getStoredDevicesForUser(userId);
const anyDeviceNotVerified = devices.some(({ deviceId }) => {

View file

@ -181,7 +181,7 @@ export function setCryptoInitialised(cryptoInited: boolean): void {
/* Simple wrapper functions around IndexedDB.
*/
let idb: IDBDatabase = null;
let idb: IDBDatabase | null = null;
async function idbInit(): Promise<void> {
if (!indexedDB) {
@ -206,7 +206,7 @@ export async function idbLoad(table: string, key: string | string[]): Promise<an
await idbInit();
}
return new Promise((resolve, reject) => {
const txn = idb.transaction([table], "readonly");
const txn = idb!.transaction([table], "readonly");
txn.onerror = reject;
const objectStore = txn.objectStore(table);
@ -223,7 +223,7 @@ export async function idbSave(table: string, key: string | string[], data: any):
await idbInit();
}
return new Promise((resolve, reject) => {
const txn = idb.transaction([table], "readwrite");
const txn = idb!.transaction([table], "readwrite");
txn.onerror = reject;
const objectStore = txn.objectStore(table);
@ -240,7 +240,7 @@ export async function idbDelete(table: string, key: string | string[]): Promise<
await idbInit();
}
return new Promise((resolve, reject) => {
const txn = idb.transaction([table], "readwrite");
const txn = idb!.transaction([table], "readwrite");
txn.onerror = reject;
const objectStore = txn.objectStore(table);

View file

@ -26,8 +26,8 @@ Once a timer is finished or aborted, it can't be started again
a new one through `clone()` or `cloneIfRun()`.
*/
export default class Timer {
private timerHandle: number;
private startTs: number;
private timerHandle?: number;
private startTs?: number;
private promise: Promise<void>;
private resolve: () => void;
private reject: (Error) => void;
@ -37,19 +37,19 @@ export default class Timer {
}
private setNotStarted(): void {
this.timerHandle = null;
this.startTs = null;
this.timerHandle = undefined;
this.startTs = undefined;
this.promise = new Promise<void>((resolve, reject) => {
this.resolve = resolve;
this.reject = reject;
}).finally(() => {
this.timerHandle = null;
this.timerHandle = undefined;
});
}
private onTimeout = (): void => {
const now = Date.now();
const elapsed = now - this.startTs;
const elapsed = now - this.startTs!;
if (elapsed >= this.timeout) {
this.resolve();
this.setNotStarted();
@ -124,6 +124,6 @@ export default class Timer {
}
public isRunning(): boolean {
return this.timerHandle !== null;
return this.timerHandle !== undefined;
}
}

View file

@ -31,7 +31,7 @@ export function abbreviateUrl(u: string): string {
if (parsedUrl.path === "/") {
// we ignore query / hash parts: these aren't relevant for IS server URLs
return parsedUrl.host;
return parsedUrl.host || "";
}
return u;

View file

@ -266,7 +266,7 @@ export class ArrayUtil<T> {
const obj = this.a.reduce((rv: Map<K, T[]>, val: T) => {
const k = fn(val);
if (!rv.has(k)) rv.set(k, []);
rv.get(k).push(val);
rv.get(k)!.push(val);
return rv;
}, new Map<K, T[]>());
return new GroupedArray(obj);
@ -299,7 +299,7 @@ export class GroupedArray<K, T> {
const a: T[] = [];
for (const k of keyOrder) {
if (!this.val.has(k)) continue;
a.push(...this.val.get(k));
a.push(...this.val.get(k)!);
}
return new ArrayUtil(a);
}

View file

@ -39,7 +39,7 @@ import { SdkContextClass } from "../contexts/SDKContext";
export async function leaveRoomBehaviour(roomId: string, retry = true, spinner = true): Promise<void> {
let spinnerModal: IHandle<any>;
if (spinner) {
spinnerModal = Modal.createDialog(Spinner, null, "mx_Dialog_spinner");
spinnerModal = Modal.createDialog(Spinner, undefined, "mx_Dialog_spinner");
}
const cli = MatrixClientPeg.get();

View file

@ -79,14 +79,13 @@ const ANY_REGEX = /.*/;
// the list and magically have the link work.
export class RoomPermalinkCreator {
private room: Room;
private roomId: string;
private highestPlUserId: string;
private populationMap: { [serverName: string]: number };
private bannedHostsRegexps: RegExp[];
private allowedHostsRegexps: RegExp[];
private _serverCandidates: string[];
private started: boolean;
private highestPlUserId: string | null = null;
private populationMap: { [serverName: string]: number } | null = null;
private bannedHostsRegexps: RegExp[] | null = null;
private allowedHostsRegexps: RegExp[] | null = null;
private _serverCandidates: string[] | null = null;
private started = false;
// We support being given a roomId as a fallback in the event the `room` object
// doesn't exist or is not healthy for us to rely on. For example, loading a
@ -94,15 +93,8 @@ export class RoomPermalinkCreator {
// Some of the tests done by this class are relatively expensive, so normally
// throttled to not happen on every update. Pass false as the shouldThrottle
// param to disable this behaviour, eg. for tests.
public constructor(room: Room, roomId: string | null = null, shouldThrottle = true) {
this.room = room;
this.roomId = room ? room.roomId : roomId;
this.highestPlUserId = null;
this.populationMap = null;
this.bannedHostsRegexps = null;
this.allowedHostsRegexps = null;
this._serverCandidates = null;
this.started = false;
public constructor(private room: Room, roomId: string | null = null, shouldThrottle = true) {
this.roomId = room ? room.roomId : roomId!;
if (!this.roomId) {
throw new Error("Failed to resolve a roomId for the permalink creator to use");
@ -316,7 +308,7 @@ export function isPermalinkHost(host: string): boolean {
* @param {string} entity The entity to transform.
* @returns {string|null} The transformed permalink or null if unable.
*/
export function tryTransformEntityToPermalink(entity: string): string {
export function tryTransformEntityToPermalink(entity: string): string | null {
if (!entity) return null;
// Check to see if it is a bare entity for starters
@ -391,7 +383,7 @@ export function tryTransformPermalinkToLocalHref(permalink: string): string {
return permalink;
}
export function getPrimaryPermalinkEntity(permalink: string): string {
export function getPrimaryPermalinkEntity(permalink: string): string | null {
try {
let permalinkParts = parsePermalink(permalink);
@ -425,7 +417,7 @@ function getPermalinkConstructor(): PermalinkConstructor {
return new MatrixToPermalinkConstructor();
}
export function parsePermalink(fullUrl: string): PermalinkParts {
export function parsePermalink(fullUrl: string): PermalinkParts | null {
try {
const elementPrefix = SdkConfig.get("permalink_prefix");
if (decodeURIComponent(fullUrl).startsWith(matrixtoBaseUrl)) {

View file

@ -41,7 +41,7 @@ import { OpenAddExistingToSpaceDialogPayload } from "../dispatcher/payloads/Open
import { SdkContextClass } from "../contexts/SDKContext";
export const shouldShowSpaceSettings = (space: Room): boolean => {
const userId = space.client.getUserId();
const userId = space.client.getUserId()!;
return (
space.getMyMembership() === "join" &&
(space.currentState.maySendStateEvent(EventType.RoomAvatar, userId) ||
@ -88,7 +88,7 @@ export const showCreateNewRoom = async (space: Room, type?: RoomType): Promise<b
};
export const shouldShowSpaceInvite = (space: Room): boolean =>
((space?.getMyMembership() === "join" && space.canInvite(space.client.getUserId())) ||
((space?.getMyMembership() === "join" && space.canInvite(space.client.getUserId()!)) ||
space.getJoinRule() === JoinRule.Public) &&
shouldShowComponent(UIComponent.InviteUsers);
@ -149,7 +149,7 @@ export const bulkSpaceBehaviour = async (
children: Room[],
fn: (room: Room) => Promise<unknown>,
): Promise<void> => {
const modal = Modal.createDialog(Spinner, null, "mx_Dialog_spinner");
const modal = Modal.createDialog(Spinner, undefined, "mx_Dialog_spinner");
try {
for (const room of children) {
await fn(room);

View file

@ -47,9 +47,9 @@ export function tooltipifyLinks(rootNodes: ArrayLike<Element>, ignoredNodes: Ele
if (
node.tagName === "A" &&
node.getAttribute("href") &&
node.getAttribute("href") !== node.textContent.trim()
node.getAttribute("href") !== node.textContent?.trim()
) {
let href = node.getAttribute("href");
let href = node.getAttribute("href")!;
try {
href = new URL(href, window.location.href).toString();
} catch (e) {