Skip to content

Instantly share code, notes, and snippets.

@NileDaley
Created May 7, 2019 12:28
Show Gist options
  • Save NileDaley/148a4b4e4639659eac34c0c9825a902c to your computer and use it in GitHub Desktop.
Save NileDaley/148a4b4e4639659eac34c0c9825a902c to your computer and use it in GitHub Desktop.
Utils - Typescript
type HandleResponse<T> = HandleResult<T> | HandleError;
type HandleResult<T> = [null, T];
type HandleError = [Error, null];
export const handle = async <T = any>(prom: Promise<T>): Promise<HandleResponse<T>> => {
try {
const res = await prom;
return [null, res] as HandleResult<T>;
} catch (err) {
return [err, null] as HandleError;
}
};
/**
* Returns true if subject has a key of prop
* @example
* interface Foo { bar: string };
* const foo: Foo = { bar: 'hello' };
* isProperty('bar', foo); // True
* isProperty('bob', foo); // False
*/
export function isProperty<T>(prop: any, subject: T): prop is keyof T {
// Same as Object.keys(subject).indexOf(prop) > -1
return prop in subject;
}
export default isProperty;
export function path(obj: { [key: string]: any }, path: string) {
var o = obj;
var elems = path.split('.');
var lim = elems.length;
for (let i = 0; i < lim; i++) {
let key = elems[i];
if (!o[key]) {
return o[key];
} else {
o = o[key];
}
}
return o;
}
export default path;
/**
* @description
* Set the value of an element using the native value setter instead of element.value = 'my value'
* This triggers other react events that look at the native value i.e. onChange
* @see https://github.com/facebook/react/issues/10135#issuecomment-314441175
* @example
* myElement.value = 'set my value';
* myElement.dispatchEvent(new Event('change', { bubbles: true })); // This will NOT trigger React's onChange handler
*
* setNativeValue(myElement, 'set my value');
* myElement.dispatchEvent(new Event('change', { bubbles: true })); // This WILL trigger React's onChange handler
*/
export const setNativeValue = (element: any, value: string): void => {
const valueSetter = Object.getOwnPropertyDescriptor(element, 'value')!.set;
const prototype = Object.getPrototypeOf(element);
const prototypeValueSetter = Object.getOwnPropertyDescriptor(prototype, 'value')!.set;
if (valueSetter && valueSetter !== prototypeValueSetter) {
prototypeValueSetter!.call(element, value);
} else {
valueSetter!.call(element, value);
}
};
export default setNativeValue;
export async function sleep(ms: number): Promise<void> {
return new Promise(resolve => {
setTimeout(resolve, ms);
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment