1
0
mirror of https://github.com/matrix-org/matrix-js-sdk.git synced 2025-11-25 05:23:13 +03:00

Improve typing (#2352)

* Fix typing of the store interface

* Fix typed s'more

* re-add check

* Be less dumb

* arg

* Fix types
This commit is contained in:
Michael Telatynski
2022-05-09 11:58:52 +01:00
committed by GitHub
parent da69ca215b
commit 706b4d6054
16 changed files with 25 additions and 20 deletions

View File

@@ -23,6 +23,7 @@ declare global {
// use `number` as the return type in all cases for global.set{Interval,Timeout}, // use `number` as the return type in all cases for global.set{Interval,Timeout},
// so we don't accidentally use the methods on NodeJS.Timeout - they only exist in a subset of environments. // so we don't accidentally use the methods on NodeJS.Timeout - they only exist in a subset of environments.
// The overload for clear{Interval,Timeout} is resolved as expected. // The overload for clear{Interval,Timeout} is resolved as expected.
// We use `ReturnType<typeof setTimeout>` in the code to be agnostic of if this definition gets loaded.
function setInterval(handler: TimerHandler, timeout: number, ...arguments: any[]): number; function setInterval(handler: TimerHandler, timeout: number, ...arguments: any[]): number;
function setTimeout(handler: TimerHandler, timeout: number, ...arguments: any[]): number; function setTimeout(handler: TimerHandler, timeout: number, ...arguments: any[]): number;

View File

@@ -913,7 +913,7 @@ export class MatrixClient extends TypedEventEmitter<EmittedEvents, ClientEventHa
protected syncLeftRoomsPromise: Promise<Room[]>; protected syncLeftRoomsPromise: Promise<Room[]>;
protected syncedLeftRooms = false; protected syncedLeftRooms = false;
protected clientOpts: IStoredClientOpts; protected clientOpts: IStoredClientOpts;
protected clientWellKnownIntervalID: number; protected clientWellKnownIntervalID: ReturnType<typeof setInterval>;
protected canResetTimelineCallback: ResetTimelineCallback; protected canResetTimelineCallback: ResetTimelineCallback;
// The pushprocessor caches useful things, so keep one and re-use it // The pushprocessor caches useful things, so keep one and re-use it
@@ -931,7 +931,7 @@ export class MatrixClient extends TypedEventEmitter<EmittedEvents, ClientEventHa
protected clientWellKnownPromise: Promise<IClientWellKnown>; protected clientWellKnownPromise: Promise<IClientWellKnown>;
protected turnServers: ITurnServer[] = []; protected turnServers: ITurnServer[] = [];
protected turnServersExpiry = 0; protected turnServersExpiry = 0;
protected checkTurnServersIntervalID: number; protected checkTurnServersIntervalID: ReturnType<typeof setInterval>;
protected exportedOlmDeviceToImport: IOlmDevice; protected exportedOlmDeviceToImport: IOlmDevice;
protected txnCtr = 0; protected txnCtr = 0;
protected mediaHandler = new MediaHandler(this); protected mediaHandler = new MediaHandler(this);

View File

@@ -95,7 +95,7 @@ export class DeviceList extends TypedEventEmitter<EmittedEvents, CryptoEventHand
// The time the save is scheduled for // The time the save is scheduled for
private savePromiseTime: number = null; private savePromiseTime: number = null;
// The timer used to delay the save // The timer used to delay the save
private saveTimer: number = null; private saveTimer: ReturnType<typeof setTimeout> = null;
// True if we have fetched data from the server or loaded a non-empty // True if we have fetched data from the server or loaded a non-empty
// set of device data from the store // set of device data from the store
private hasFetched: boolean = null; private hasFetched: boolean = null;

View File

@@ -78,7 +78,7 @@ export enum RoomKeyRequestState {
export class OutgoingRoomKeyRequestManager { export class OutgoingRoomKeyRequestManager {
// handle for the delayed call to sendOutgoingRoomKeyRequests. Non-null // handle for the delayed call to sendOutgoingRoomKeyRequests. Non-null
// if the callback has been set, or if it is still running. // if the callback has been set, or if it is still running.
private sendOutgoingRoomKeyRequestsTimer: number = null; private sendOutgoingRoomKeyRequestsTimer: ReturnType<typeof setTimeout> = null;
// sanity check to ensure that we don't end up with two concurrent runs // sanity check to ensure that we don't end up with two concurrent runs
// of sendOutgoingRoomKeyRequests // of sendOutgoingRoomKeyRequests

View File

@@ -309,7 +309,7 @@ export class Crypto extends TypedEventEmitter<CryptoEvent, CryptoEventHandlerMap
private oneTimeKeyCount: number; private oneTimeKeyCount: number;
private needsNewFallback: boolean; private needsNewFallback: boolean;
private fallbackCleanup?: number; // setTimeout ID private fallbackCleanup?: ReturnType<typeof setTimeout>;
/** /**
* Cryptography bits * Cryptography bits

View File

@@ -14,7 +14,7 @@ See the License for the specific language governing permissions and
limitations under the License. limitations under the License.
*/ */
import bs58 from 'bs58'; import * as bs58 from 'bs58';
// picked arbitrarily but to try & avoid clashing with any bitcoin ones // picked arbitrarily but to try & avoid clashing with any bitcoin ones
// (which are also base58 encoded, but bitcoin's involve a lot more hashing) // (which are also base58 encoded, but bitcoin's involve a lot more hashing)

View File

@@ -873,7 +873,7 @@ export class Backend implements CryptoStore {
public doTxn<T>( public doTxn<T>(
mode: Mode, mode: Mode,
stores: Iterable<string>, stores: string | string[],
func: (txn: IDBTransaction) => T, func: (txn: IDBTransaction) => T,
log: PrefixedLogger = logger, log: PrefixedLogger = logger,
): Promise<T> { ): Promise<T> {

View File

@@ -55,7 +55,7 @@ export class VerificationBase<
private cancelled = false; private cancelled = false;
private _done = false; private _done = false;
private promise: Promise<void> = null; private promise: Promise<void> = null;
private transactionTimeoutTimer: number = null; private transactionTimeoutTimer: ReturnType<typeof setTimeout> = null;
protected expectedEvent: string; protected expectedEvent: string;
private resolve: () => void; private resolve: () => void;
private reject: (e: Error | MatrixEvent) => void; private reject: (e: Error | MatrixEvent) => void;

View File

@@ -95,7 +95,7 @@ export class VerificationRequest<
private eventsByUs = new Map<string, MatrixEvent>(); private eventsByUs = new Map<string, MatrixEvent>();
private eventsByThem = new Map<string, MatrixEvent>(); private eventsByThem = new Map<string, MatrixEvent>();
private _observeOnly = false; private _observeOnly = false;
private timeoutTimer: number = null; private timeoutTimer: ReturnType<typeof setTimeout> = null;
private _accepting = false; private _accepting = false;
private _declining = false; private _declining = false;
private verifierHasFinished = false; private verifierHasFinished = false;

View File

@@ -14,7 +14,7 @@ See the License for the specific language governing permissions and
limitations under the License. limitations under the License.
*/ */
import request from "request"; import * as request from "request";
import * as matrixcs from "./matrix"; import * as matrixcs from "./matrix";
import * as utils from "./utils"; import * as utils from "./utils";

View File

@@ -54,7 +54,7 @@ export class Beacon extends TypedEventEmitter<Exclude<BeaconEvent, BeaconEvent.N
public readonly roomId: string; public readonly roomId: string;
private _beaconInfo: BeaconInfoState; private _beaconInfo: BeaconInfoState;
private _isLive: boolean; private _isLive: boolean;
private livenessWatchInterval: number; private livenessWatchInterval: ReturnType<typeof setInterval>;
private _latestLocationState: BeaconLocationState | undefined; private _latestLocationState: BeaconLocationState | undefined;
constructor( constructor(

View File

@@ -37,6 +37,10 @@ export interface ISavedSync {
export interface IStore { export interface IStore {
readonly accountData: Record<string, MatrixEvent>; // type : content readonly accountData: Record<string, MatrixEvent>; // type : content
// XXX: The indexeddb store exposes a non-standard emitter for the "degraded" event
// for when it falls back to being a memory store due to errors.
on?: (event: string, handler: (...args: any[]) => void) => void;
/** @return {Promise<boolean>} whether or not the database was newly created in this session. */ /** @return {Promise<boolean>} whether or not the database was newly created in this session. */
isNewlyCreated(): Promise<boolean>; isNewlyCreated(): Promise<boolean>;
@@ -105,7 +109,7 @@ export interface IStore {
/** /**
* No-op. * No-op.
* @param {Room} room * @param {Room} room
* @param {integer} limit * @param {number} limit
* @return {Array} * @return {Array}
*/ */
scrollback(room: Room, limit: number): MatrixEvent[]; scrollback(room: Room, limit: number): MatrixEvent[];

View File

@@ -152,7 +152,7 @@ export class SyncApi {
private syncStateData: ISyncStateData = null; // additional data (eg. error object for failed sync) private syncStateData: ISyncStateData = null; // additional data (eg. error object for failed sync)
private catchingUp = false; private catchingUp = false;
private running = false; private running = false;
private keepAliveTimer: number = null; private keepAliveTimer: ReturnType<typeof setTimeout> = null;
private connectionReturnedDefer: IDeferred<boolean> = null; private connectionReturnedDefer: IDeferred<boolean> = null;
private notifEvents: MatrixEvent[] = []; // accumulator of sync events in the current sync response private notifEvents: MatrixEvent[] = []; // accumulator of sync events in the current sync response
private failedSyncCount = 0; // Number of consecutive failed /sync requests private failedSyncCount = 0; // Number of consecutive failed /sync requests
@@ -1390,7 +1390,7 @@ export class SyncApi {
* Starts polling the connectivity check endpoint * Starts polling the connectivity check endpoint
* @param {number} delay How long to delay until the first poll. * @param {number} delay How long to delay until the first poll.
* defaults to a short, randomised interval (to prevent * defaults to a short, randomised interval (to prevent
* tightlooping if /versions succeeds but /sync etc. fail). * tight-looping if /versions succeeds but /sync etc. fail).
* @return {promise} which resolves once the connection returns * @return {promise} which resolves once the connection returns
*/ */
private startKeepAlives(delay?: number): Promise<boolean> { private startKeepAlives(delay?: number): Promise<boolean> {

View File

@@ -23,7 +23,7 @@ limitations under the License.
import unhomoglyph from "unhomoglyph"; import unhomoglyph from "unhomoglyph";
import promiseRetry from "p-retry"; import promiseRetry from "p-retry";
import type NodeCrypto from "crypto"; import type * as NodeCrypto from "crypto";
import { MatrixEvent } from "."; import { MatrixEvent } from ".";
import { M_TIMESTAMP } from "./@types/location"; import { M_TIMESTAMP } from "./@types/location";

View File

@@ -298,7 +298,7 @@ export class MatrixCall extends TypedEventEmitter<CallEvent, CallEventHandlerMap
// yet, null if we have but they didn't send a party ID. // yet, null if we have but they didn't send a party ID.
private opponentPartyId: string; private opponentPartyId: string;
private opponentCaps: CallCapabilities; private opponentCaps: CallCapabilities;
private inviteTimeout: number; private inviteTimeout: ReturnType<typeof setTimeout>;
// The logic of when & if a call is on hold is nontrivial and explained in is*OnHold // The logic of when & if a call is on hold is nontrivial and explained in is*OnHold
// This flag represents whether we want the other party to be on hold // This flag represents whether we want the other party to be on hold
@@ -322,7 +322,7 @@ export class MatrixCall extends TypedEventEmitter<CallEvent, CallEventHandlerMap
private remoteSDPStreamMetadata: SDPStreamMetadata; private remoteSDPStreamMetadata: SDPStreamMetadata;
private callLengthInterval: number; private callLengthInterval: ReturnType<typeof setInterval>;
private callLength = 0; private callLength = 0;
constructor(opts: CallOpts) { constructor(opts: CallOpts) {
@@ -708,9 +708,9 @@ export class MatrixCall extends TypedEventEmitter<CallEvent, CallEventHandlerMap
const statsReport = await this.peerConn.getStats(); const statsReport = await this.peerConn.getStats();
const stats = []; const stats = [];
for (const item of statsReport) { statsReport.forEach(item => {
stats.push(item[1]); stats.push(item[1]);
} });
return stats; return stats;
} }

View File

@@ -69,7 +69,7 @@ export class CallFeed extends TypedEventEmitter<CallFeedEvent, EventHandlerMap>
private frequencyBinCount: Float32Array; private frequencyBinCount: Float32Array;
private speakingThreshold = SPEAKING_THRESHOLD; private speakingThreshold = SPEAKING_THRESHOLD;
private speaking = false; private speaking = false;
private volumeLooperTimeout: number; private volumeLooperTimeout: ReturnType<typeof setTimeout>;
constructor(opts: ICallFeedOpts) { constructor(opts: ICallFeedOpts) {
super(); super();