TypeScript One-Liners to Use in Every Project

Mahmadmustafa M kaladagi
2 min readSep 3, 2023

--

TypeScript is a powerful language that can do a lot with very little code.
In some cases, the amount of code we need to write doesn’t exceed more than a single line, which is why they are known as one-liners.
Some essential one liners worth using in virtually every TypeScript project we create.

/* checkFor empty Array */
static isArrayEmpty = (array: any) => !Array.isArray(array) || array.length === 0;
/* checkFor empty Object */
static isObjectEmpty = (object: any) => JSON.stringify(object) === "{}" || Object.keys(object).length === 0;
/* checkFor empty value */
static isEmpty = (str: any) => (!str || str.length === 0);
/* get in JSON format (deepCopy) */
static singleBindAssignObject = (inputObject: any) => JSON.parse(JSON.stringify(inputObject));
/* get query params from URL */
static getParmFromUrl = (query: string) => (new URLSearchParams(location.search)).get(query) ?? '';
/* generate random number */
static getUniqueSessionValue = () => Date.now().toString(+'36') + Math.random().toString(+'36').substring(+'2');
/* capitalize first letter of each word */
static capitalize = (value: string) => value?.toLowerCase().trim().replace(/ +/g, ' ').replace(/\b./g, (m: string) => m.toUpperCase()) || '';
/* To Pluck Property from Array of Objects */
static pluck = (array: any, key: string) => array?.map((item: any) => item[key]) || '';
/* To Wait for a Certain Amount of Time */
static wait = async (milliSeconds: number) => new Promise((resolve) => setTimeout(resolve, milliSeconds));
/* copy text to Clipboard */
static async copyToClipboard(text: string) {
try {
await navigator.clipboard.writeText(text);
} catch (err) {
console.error('Error in copying text: ', err);
}
}
/* generate number list; ex- range(2001,10,true) */
static range = (start: number, total: number, increment: boolean = true) => {
return increment ? Array.from({ length: total }, (_, i) => start + i) : Array.from({ length: total }, (_, i) => start - i);
}
/* get origin from URL */    
static origin = (baseUrl: string) => (new URL(baseUrl)).origin;

/* get href from URL */
static path = (baseUrl: string) => (new URL(baseUrl)).href;
/* detect device */
static detectDeviceType = () => /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ? 'Mobile' : 'Desktop';
/* add event listner to target element */
static listen = (target: Element, event: string, callback: any, ...options: any) => {
return target.addEventListener(event, callback, ...options);
};

--

--

Mahmadmustafa M kaladagi

Experienced Angular Developer with 5+ years of experience in developing user-facing applications using Angular Framework.