Typescript can be challenging and getting used to the intricacies of adding typing to traditional JavaScript can be quite confusing. This collection is aimed at helping you perform common TypeScript and JavaScript operations using typing and will be useful for all developer levels from beginners to advanced.
Pick properties from interface
Tags: typescript, pick
Construct a new type based on partial properties of an interface.
interface MyInterface {
id: number;
name: string;
properties: string[];
}
type MyShortType = Pick;
Related links:
- https://www.typescriptlang.org/docs/handbook/utility-types.html
- https://www.becomebetterprogrammer.com/typescript-pick-type/
Omit properties from interface
Tags: typescript, omit
Exclude properties from a given interface.
interface MyInterface {
id: number;
name: string;
properties: string[];
}
type MyShortType = Omit;
Related links:
- https://www.typescriptlang.org/docs/handbook/utility-types.html
- https://mariusschulz.com/blog/the-omit-helper-type-in-typescript
Get Value
Tags: typescript, get value
Get value of an object with an interface.
interface MyInterface {
id: number;
name: string;
properties: string[];
}
const myObject: MyInterface = {
id: 1,
name: 'foo',
properties: ['a', 'b', 'c']
};
function getValue(value: keyof MyInterface) {
return myObject[value];
}
getValue('id'); // 1
getValue('count')
Related links:
- https://www.typescriptlang.org/docs/handbook/2/keyof-types.html
Store record as a string with interface
Tags: typescript, record
Map a string key to a custom interface in an object.
const myTypedObject: Record = {
first: {...},
second: {...},
...
};
Related links:
- https://www.typescriptlang.org/docs/handbook/utility-types.html
- https://stackoverflow.com/questions/51936369/what-is-the-record-type-in-typescript
- https://betterprogramming.pub/typescripts-record-type-explained-691372b1a449
Check if collection elements are true
Tags: typescript, every, collection
Returns true if all elements in a collection are true.
const all = (arr: T[], fn: (t: T) => boolean = Boolean) => arr.every(fn);
Related links:
- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/every
- https://www.tutorialspoint.com/typescript/typescript_array_every.htm
Check if at least one element passes function
Tags: typescript, some
Tests whether at least one element in the array passes the test implemented by a provided function.
const some = (arr: T[], fn: (t: T) => boolean = Boolean) => arr.some(fn);
Related links:
- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some
- https://www.tutorialspoint.com/typescript/typescript_array_some.htm
Remove falsy values
Tags: typescript, filter, compact
Removes falsy values from an array.
const compact = (arr: any[]) => arr.filter(Boolean);
Related links:
- https://stackoverflow.com/questions/32906887/remove-all-falsy-values-from-an-array
- https://bobbyhadz.com/blog/typescript-remove-null-from-array
Delay async executions
Tags: typescript, async, setTimeout
Turns setTimeout into a promise that can be used asynchronously.
const timeoutPromise: (duration: number) => Promise = (duration: number): Promise => new Promise(resolver => setTimeout(resolver, duration));
Related links:
- https://stackoverflow.com/questions/33289726/combination-of-async-function-await-settimeout
- https://stackoverflow.com/questions/51200626/using-a-settimeout-in-a-async-function
- https://dev.to/bbarbour/making-settimeout-async-friendly-50je
Function composition
Tags: typescript, composition
Performs left to right function composition.
const compose = (...fns: Func[]) => {
fns.reduce((f, g) => (...args: any[]) => f(...castArray(g(...args))));
}
Related links:
- https://www.educative.io/answers/function-composition-in-javascript
- https://jrsinclair.com/articles/2022/javascript-function-composition-whats-the-big-deal/
Debounce
Tags: typescript, debounce
Delays invoking a provided function at least since specified milliseconds have elapsed.
const debounce = (fn: Function, ms = 300) => {
let timeoutId: ReturnType;
return function (this: any, ...args: any[]) {
clearTimeout(timeoutId);
timeoutId = setTimeout(() => fn.apply(this, args), ms);
};
};
Related links:
- https://www.freecodecamp.org/news/javascript-debounce-example/
- https://stackoverflow.com/questions/59104425/typescript-debounce-function-not-calling-function-passed-as-parameter
Deep Clone
Tags: typescript, clone, deep clone
Creates a deep clone of an object.
const deepClone = (obj: any) => {
if (obj === null) return null;
let clone = { ...obj };
Object.keys(clone).forEach(
(key) =>
(clone[key] = typeof obj[key] === "object" ? deepClone(obj[key]) : obj[key])
);
return Array.isArray(obj) && obj.length
? (clone.length = obj.length) && Array.from(clone)
: Array.isArray(obj)
? Array.from(obj)
: clone;
};
Related links:
- https://javascript.plainenglish.io/deep-clone-an-object-and-preserve-its-type-with-typescript-d488c35e5574
- https://stackoverflow.com/questions/34201483/deep-clone-in-typescript-preserving-types
Find key
Tags: typescript, find key
Returns the first key that meets a condition specified from passed function.
const findKey = (obj: any, fn: Function) => Object.keys(obj).find((key) => fn(obj[key], key, obj));
Related links:
- https://bobbyhadz.com/blog/typescript-object-get-key-by-value
- https://stackoverflow.com/questions/38292652/typescript-find-key-value-in-object-list-comprehension
Intersection
Tags: typescript, intersection
Returns a list of elements that exist in both arrays.
const intersection = (a: any[], b: any[]) => {",
const s = new Set(b);
return [...new Set(a)].filter((x) => s.has(x));
};
Related links:
- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set
- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/has
Is empty
Tags: typescript, is empty
Checks if a value is an empty object, array, or null.
const isEmpty = (val: any) => val == null || !(Object.keys(val) || val.length;
Related links:
- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys
- https://stackoverflow.com/questions/19146176/why-do-empty-javascript-arrays-evaluate-to-true-in-conditional-structures
Async
Tags: typescript, async
Create a promise using typescript with a void return value.
const fetchData = async (): Promise => {
// ...
};
Related links:
- https://blog.logrocket.com/async-await-in-typescript/
- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise
Array to Object
Tags: typescript, array to object
Turns an Array into an Object.
const arrayToObj = (array: T[]): { [k: string]: T } => {
const out: { [k: string]: T } = {};
array.forEach((val) => {
out[val.id] = val;
});
return out;
};
Related links:
- https://stackoverflow.com/questions/50802528/convert-js-array-to-dictionary-hashmap