Typescript Snippets

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

Add to Pieces

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.

How to pick properties from interface in TypeScript

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:

  1. TypeScript utility types
  2. How to use pick in TypeScript

How to use TypeScript to exclude a property from an interface

Tags: typescript, omit

Exclude properties from a given interface with this TypeScript snippet.

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

type MyShortType = Omit;

Related links:

  1. TypeScript utility types
  2. Omit type in TypeScript

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

Tags: typescript, get value

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

Related links:

  1. Keyof TypeScript snippets

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

Tags: typescript, record

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

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

Related links:

  1. TypeScript utility types
  2. Record typed in TypeScript
  3. TypeScript record type explained

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

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:

  1. Array prototype every - TypeScript code snippets
  2. TypeScript Array Every

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

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:

  1. Array Prototype Some - TypeScript example
  2. TypeScript Array Some Examples

How to remove falsy values from an array using TypeScript

Tags: typescript, filter, compact

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

Related links:

  1. Remove all falsy values from an array

How to delay async executions using TypeScript

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:

  1. Combination of functions - Async + wait + setTimeout
  2. Using a setTimeout in an async function - Typescript Snippets
  3. How to make TypeScript setTimeout async friendly

TypeScript 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:

  1. Function composition in Javascript - Explained
  2. How to do function composition in JavaScript

TypeScript debounce example

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:

  1. How to delay a function in JavaScript - Debounce example
  2. TypeScript Debounce function - troubleshooting

How to create a deep clone in TypeScript

Tags: typescript, clone, deep clone

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

Related links:

  1. Deep Clone an Object and Preserve its Type - TypeScript code sample
  2. Deep clone TypeScript - Troubleshooting

How to find the key that meets a condition in TypeScript

Tags: typescript, find key

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

Related links:

  1. How to get an Object's Key by Value in TypeScript
  2. How to find key and value in object JavaScript

Find intersection of two arrays using TypeScript

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:

  1. Set JavaScript example
  2. Map Prototype Has - JavaScript examples

How to check if an array is empty in TypeScript

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:

  1. TypeScript check if object is empty
  2. Why do empty JavaScript arrays evaluate to true in conditional structures?

How to use Async in TypeScript

Tags: typescript, async

Create a promise using Typescript with a void return value.

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

Related links:

  1. How to use async await in TypeScript
  2. How to create a promise function in JavaScript

How to convert object to array in TypeScript

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:

  1. How to Convert a JavaScript Array to Dictionary / Hashmap

Want to use these TypeScript snippets in your IDE? Download our JetBrains plugin or VS Code extension to improve your developer productivity wherever you code.

Let us know what you think! Would you like to see other TypeScript snippets not listed on this page? Suggest a collection you'd like to see to help other developers speed up their workflows.