Make more code conform to strict null checks (#10219

* Make more code conform to strict null checks

* Fix types

* Fix tests

* Fix remaining test assertions

* Iterate PR
This commit is contained in:
Michael Telatynski 2023-02-24 15:28:40 +00:00 committed by GitHub
parent 4c79ecf141
commit 76b82b4b2b
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
130 changed files with 603 additions and 603 deletions

View file

@ -218,17 +218,20 @@ export function shouldDisplayReply(event: MatrixEvent): boolean {
return !!inReplyTo.event_id;
}
interface IAddReplyOpts {
interface AddReplyOpts {
permalinkCreator?: RoomPermalinkCreator;
includeLegacyFallback?: boolean;
includeLegacyFallback: false;
}
interface IncludeLegacyFeedbackOpts {
permalinkCreator: RoomPermalinkCreator;
includeLegacyFallback: true;
}
export function addReplyToMessageContent(
content: IContent,
replyToEvent: MatrixEvent,
opts: IAddReplyOpts = {
includeLegacyFallback: true,
},
opts: AddReplyOpts | IncludeLegacyFeedbackOpts,
): void {
content["m.relates_to"] = {
...(content["m.relates_to"] || {}),

View file

@ -64,7 +64,7 @@ interface IActivityScore {
// We do this by checking every room to see who has sent a message in the last few hours, and giving them
// a score which correlates to the freshness of their message. In theory, this results in suggestions
// which are closer to "continue this conversation" rather than "this person exists".
export function buildActivityScores(cli: MatrixClient): { [key: string]: IActivityScore } {
export function buildActivityScores(cli: MatrixClient): { [key: string]: IActivityScore | undefined } {
const now = new Date().getTime();
const earliestAgeConsidered = now - 60 * 60 * 1000; // 1 hour ago
const maxMessagesConsidered = 50; // so we don't iterate over a huge amount of traffic
@ -73,7 +73,8 @@ export function buildActivityScores(cli: MatrixClient): { [key: string]: IActivi
.filter((ev) => ev.getTs() > earliestAgeConsidered);
const senderEvents = groupBy(events, (ev) => ev.getSender());
return mapValues(senderEvents, (events) => {
const lastEvent = maxBy(events, (ev) => ev.getTs());
if (!events.length) return;
const lastEvent = maxBy(events, (ev) => ev.getTs())!;
const distanceFromNow = Math.abs(now - lastEvent.getTs()); // abs to account for slight future messages
const inverseTime = now - earliestAgeConsidered - distanceFromNow;
return {
@ -92,7 +93,7 @@ interface IMemberScore {
numRooms: number;
}
export function buildMemberScores(cli: MatrixClient): { [key: string]: IMemberScore } {
export function buildMemberScores(cli: MatrixClient): { [key: string]: IMemberScore | undefined } {
const maxConsideredMembers = 200;
const consideredRooms = joinedRooms(cli).filter((room) => room.getJoinedMemberCount() < maxConsideredMembers);
const memberPeerEntries = consideredRooms.flatMap((room) =>
@ -100,10 +101,11 @@ export function buildMemberScores(cli: MatrixClient): { [key: string]: IMemberSc
);
const userMeta = groupBy(memberPeerEntries, ({ member }) => member.userId);
return mapValues(userMeta, (roomMemberships) => {
if (!roomMemberships.length) return;
const maximumPeers = maxConsideredMembers * roomMemberships.length;
const totalPeers = sumBy(roomMemberships, (entry) => entry.roomSize);
return {
member: minBy(roomMemberships, (entry) => entry.roomSize).member,
member: minBy(roomMemberships, (entry) => entry.roomSize)!.member,
numRooms: roomMemberships.length,
score: Math.max(0, Math.pow(1 - totalPeers / maximumPeers, 5)),
};

View file

@ -323,3 +323,7 @@ export async function asyncEvery<T>(values: T[], predicate: (value: T) => Promis
}
return true;
}
export function filterBoolean<T>(values: Array<T | null | undefined>): T[] {
return values.filter(Boolean) as T[];
}

View file

@ -23,7 +23,7 @@ import { MatrixClient, MatrixEvent, getBeaconInfoIdentifier } from "matrix-js-sd
*/
export const getShareableLocationEventForBeacon = (event: MatrixEvent, cli: MatrixClient): MatrixEvent | null => {
const room = cli.getRoom(event.getRoomId());
const beacon = room.currentState.beacons?.get(getBeaconInfoIdentifier(event));
const beacon = room?.currentState.beacons?.get(getBeaconInfoIdentifier(event));
const latestLocationEvent = beacon?.latestLocationEvent;
if (beacon?.isLive && latestLocationEvent) {

View file

@ -39,7 +39,7 @@ export async function startDm(client: MatrixClient, targets: Member[], showSpinn
if (targetIds.length === 1) {
existingRoom = findDMForUser(client, targetIds[0]);
} else {
existingRoom = DMRoomMap.shared().getDMRoomForIdentifiers(targetIds);
existingRoom = DMRoomMap.shared().getDMRoomForIdentifiers(targetIds) ?? undefined;
}
if (existingRoom && !isLocalRoom(existingRoom)) {
dis.dispatch<ViewRoomPayload>({

View file

@ -15,10 +15,10 @@ limitations under the License.
*/
export const parseGeoUri = (uri: string): GeolocationCoordinates | undefined => {
function parse(s: string): number | undefined {
function parse(s: string): number | null {
const ret = parseFloat(s);
if (Number.isNaN(ret)) {
return undefined;
return null;
} else {
return ret;
}
@ -28,7 +28,7 @@ export const parseGeoUri = (uri: string): GeolocationCoordinates | undefined =>
if (!m) return;
const parts = m[1].split(";");
const coords = parts[0].split(",");
let uncertainty: number | undefined;
let uncertainty: number | null;
for (const param of parts.slice(1)) {
const m = param.match(/u=(.*)/);
if (m) uncertainty = parse(m[1]);
@ -38,8 +38,8 @@ export const parseGeoUri = (uri: string): GeolocationCoordinates | undefined =>
longitude: parse(coords[1]),
altitude: parse(coords[2]),
accuracy: uncertainty,
altitudeAccuracy: undefined,
heading: undefined,
speed: undefined,
altitudeAccuracy: null,
heading: null,
speed: null,
};
};

View file

@ -84,7 +84,7 @@ export class RoomPermalinkCreator {
private populationMap: { [serverName: string]: number } | null = null;
private bannedHostsRegexps: RegExp[] | null = null;
private allowedHostsRegexps: RegExp[] | null = null;
private _serverCandidates: string[] | null = null;
private _serverCandidates?: string[];
private started = false;
// We support being given a roomId as a fallback in the event the `room` object
@ -124,7 +124,7 @@ export class RoomPermalinkCreator {
this.started = false;
}
public get serverCandidates(): string[] {
public get serverCandidates(): string[] | undefined {
return this._serverCandidates;
}

View file

@ -54,7 +54,7 @@ export function midPointsBetweenStrings(
interface IEntry {
index: number;
order: string;
order?: string;
}
export const reorderLexicographically = (
@ -82,12 +82,12 @@ export const reorderLexicographically = (
let canMoveLeft = true;
const nextBase =
newOrder[toIndex + 1]?.order !== undefined
? stringToBase(newOrder[toIndex + 1].order)
? stringToBase(newOrder[toIndex + 1].order!)
: BigInt(Number.MAX_VALUE);
// check how far left we would have to mutate to fit in that direction
for (let i = toIndex - 1, j = 1; i >= 0; i--, j++) {
if (newOrder[i]?.order !== undefined && nextBase - stringToBase(newOrder[i].order) > j) break;
if (newOrder[i]?.order !== undefined && nextBase - stringToBase(newOrder[i].order!) > j) break;
leftBoundIdx = i;
}
@ -108,12 +108,12 @@ export const reorderLexicographically = (
if (canDisplaceRight) {
const prevBase =
newOrder[toIndex - 1]?.order !== undefined
? stringToBase(newOrder[toIndex - 1]?.order)
? stringToBase(newOrder[toIndex - 1].order!)
: BigInt(Number.MIN_VALUE);
// check how far right we would have to mutate to fit in that direction
for (let i = toIndex + 1, j = 1; i < newOrder.length; i++, j++) {
if (newOrder[i]?.order === undefined || stringToBase(newOrder[i].order) - prevBase > j) break;
if (newOrder[i]?.order === undefined || stringToBase(newOrder[i].order!) - prevBase > j) break;
rightBoundIdx = i;
}

View file

@ -37,7 +37,7 @@ export async function copyPlaintext(text: string): Promise<boolean> {
textArea.style.position = "fixed";
document.body.appendChild(textArea);
const selection = document.getSelection();
const selection = document.getSelection()!;
const range = document.createRange();
// range.selectNodeContents(textArea);
range.selectNode(textArea);
@ -59,7 +59,7 @@ export function selectText(target: Element): void {
const range = document.createRange();
range.selectNodeContents(target);
const selection = window.getSelection();
const selection = window.getSelection()!;
selection.removeAllRanges();
selection.addRange(range);
}
@ -80,5 +80,5 @@ export function copyNode(ref: Element): boolean {
* @returns the selected text
*/
export function getSelectedText(): string {
return window.getSelection().toString();
return window.getSelection()!.toString();
}