Typescript

These TypeScript snippets range from picking properties from an interface to removing falsy values. We made sure to offer all useful TypeScript code snippets.

If you are a TypeScript developer, add any of these snippets to Pieces for some extreme time-saving shortcuts. Coding in TypeScript can be challenging and getting used to the intricacies of adding typing to traditional JavaScript can be quite confusing. 

This collection of TypeScript examples is aimed at helping you perform common TypeScript and JavaScript operations. No matter your experience level, from beginner to advanced, the following TypeScript code samples will be useful for all developers.

Tags: typescript, pick

How to pick properties from interface in TypeScript

Construct a new type based on partial properties of an interface.

interface MyInterface {
  id: number;
  name: string;
  properties: string[];
}

type MyShortType = Pick;

Tags: typescript, omit

How to use TypeScript to exclude a property from an interface

Exclude properties from a given interface with this TypeScript snippet.

interface MyInterface {
  id: number;
  name: string;
  properties: string[];
}

type MyShortType = Omit;

Tags: typescript, get value

How to use TypeScript to get a value of an interface property

Get value of an object with an interface using this TypeScript code sample.

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')

‍Tags: typescript, record

How to store a record as a string with interface in TypeScript

Map a string key to a custom interface in an object.

const myTypedObject: Record = {
  first: {...},
  second: {...},
  ...
};

Tags: typescript, every, collection

How to check if a collection of elements are true in TypeScript

Returns true if all elements in a collection are true.

const all = (arr: T[], fn: (t: T) => boolean = Boolean) => arr.every(fn);

Tags: typescript, some

How to check if at least one element passes in a function using TypeScript

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);

Tags: typescript, filter, compact

How to remove falsy values from an array using TypeScript

Removes falsy values from an array. See our JavaScript snippets collection for the JS version of this TypeScript code snippet.

const compact = (arr: any[]) => arr.filter(Boolean);

Tags: typescript, async, setTimeout

How to delay async executions using TypeScript

Turns setTimeout into a promise that can be used asynchronously.

const timeoutPromise: (duration: number) => Promise = (duration: number): Promise => new Promise(resolver => setTimeout(resolver, duration));

Tags: typescript, composition

TypeScript function composition

Performs left to right function composition.

const compose = (...fns: Func[]) => {
	fns.reduce((f, g) => (...args: any[]) => f(...castArray(g(...args))));
}

Tags: typescript, debounce

TypeScript debounce example

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);
  };
};

Tags: typescript, clone, deep clone

How to create a deep clone in TypeScript

These TypeScript code snippets create 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;
};

Tags: typescript, find key

How to find the key that meets a condition in TypeScript

Returns the first key that meets a condition specified from the passed function.

const findKey = (obj: any, fn: Function) => Object.keys(obj).find((key) => fn(obj[key], key, obj));

Tags: typescript, intersection

Find intersection of two arrays using TypeScript

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));
};

Tags: typescript, is empty

How to check if an array is empty in TypeScript

Checks if a value is an empty object, array, or null.

const isEmpty = (val: any) => val == null || !(Object.keys(val) || val.length;

Tags: typescript, async

How to use Async in TypeScript

Create a promise using Typescript with a void return value.

const fetchData = async (): Promise => {
  // ... 
};

Tags: typescript, array to object

How to convert object to array in TypeScript

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;
};

150,000+ Installs

Want to use these Typescript code snippets in your IDE?

Install one of our IDE integrations to 10x your productivity during your next coding project.