Skip to content

Commit

Permalink
⭐️ Impl: Types - Add Types for helpers.ts
Browse files Browse the repository at this point in the history
  • Loading branch information
dominicstop committed Jan 9, 2023
1 parent 2d9b287 commit 0f33fcd
Showing 1 changed file with 25 additions and 21 deletions.
46 changes: 25 additions & 21 deletions src/functions/helpers.ts
Original file line number Diff line number Diff line change
@@ -1,37 +1,41 @@

//wrapper func for setstate that returns a promise
export function setStateAsync(that, newState) {
return new Promise((resolve) => {
that.setState(newState, () => {
resolve();
});
/** wrapper func for setState that returns a promise */
// eslint-disable-next-line consistent-this
export function setStateAsync<T>(
that: React.Component,
newState: T | ((prevState: T) => T)
) {
return new Promise<void>((resolve) => {
that.setState(newState, () => {
resolve();
});
});
};
}

//wrapper for timeout that returns a promise
export function timeout(ms) {
return new Promise(resolve => {
/** wrapper for timeout that returns a promise */
export function timeout(ms: number) {
return new Promise<void>((resolve) => {
const timeoutID = setTimeout(() => {
clearTimeout(timeoutID);
resolve();
}, ms)
}, ms);
});
};
}

export function promiseWithTimeout(ms, promise){
/** Wraps a promise that will reject if not not resolved in <ms> milliseconds */
export function promiseWithTimeout<T>(ms: number, promise: Promise<T>) {
// Create a promise that rejects in <ms> milliseconds
const timeoutPromise = new Promise((resolve, reject) => {
const timeoutPromise = new Promise<T>((_, reject) => {
const timeoutID = setTimeout(() => {
clearTimeout(timeoutID);
reject(`Promise timed out in ${ms} ms.`)
reject(`Promise timed out in ${ms} ms.`);
}, ms);
});

// Returns a race between our timeout and the passed in promise
return Promise.race([promise, timeoutPromise]);
};
}

export function isObject(value) {
const type = typeof value
return value != null && (type === 'object' || type === 'function')
};
export function isObject(value: unknown): value is object {
const type = typeof value;
return value != null && (type === 'object' || type === 'function');
}

0 comments on commit 0f33fcd

Please sign in to comment.