When dealing with a property that starts as null, how can I pass it to an anonymous callback function expecting a non-null value without TypeScript throwing errors?
I've tried wrapping the function call in an if statement to check for null at the call level, but TypeScript still complains within the callback.
The code below showcases this scenario. Certain DatabaseState
properties are allowed to be null initially.
//types.ts
export interface DatabaseState {
db: PouchDB.Database | null;
remoteDb: PouchDB.Database | null;
dbReplication: PouchDB.Replication.Sync<{}> | null;
dbSyncStatus: number;
dbSyncInfo: string;
dbSyncError: string;
}
//state typing - state: DatabaseState
//An action in database.ts
async startDatabaseSyncronisation({ state, commit, dispatch }) {
var opts = { live: true, retry: true };
if (state.remoteDb != null && state.db != null) {
/* USING AN IF STATEMENT PREVENTS TYPESCRIPT ERRORS AT THE FUNCTION CALL LEVEL */
await PouchDB.replicate(state.remoteDb, state.db, opts).on("complete",
function(info) {
/* WITHIN THE CALLBACK FUNCTION, HOWEVER, TYPESCRIPT STILL COMPLAINS ABOUT state.remoteDb and state.db
POSSIBLY BEING NULL AND NOT ACCEPTING A NULL VALUE */
let replication = PouchDB.sync(state.remoteDb, state.db, opts)
.on("paused", function(err: {}) {
dispatch("onSyncPaused", err);
})
.on("active", function() {
dispatch("onSyncActive");
})
.on("denied", function(err: {}) {
dispatch("onSyncError", err);
})
.on("error", function(err: {}) {
dispatch("onSyncError", err);
})
.on("complete", function() {});
commit(SET_DB_REPLICATION, replication);
}
);
}
},
How should I handle these kind of type checks? Is there a more "TypeScript-friendly" way to represent an initial value as unset?
This project is built using Vue, with Vuex for state management.