Skip to content

Typescript – cheat sheet

This cheat sheet contains typescript definitions that I sometimes use during development and that often can be easily forgotten. All examples are published on my codepen.io account so that you can directly edit and test them. They are also available in my codepen collection typescript cheat sheet. This cheat sheet is a work in progress and I will continue to add new sections.


Wrapper function

A wrapper function is a function that has the same signature as the target function it wraps. Wrapper functions are used applying aspect-oriented programming or a kind of implementation of the decorator pattern.


Function object

Every function in JavaScript is also an object and can therefore contain properties or even other functions. The typescript definition for funtions objects is a bit strange and therefore I included it in my cheat sheet.

The funtion object’s type can also directly be applied to the function instead of the variable. But this doesn’t work in codepen, but when I complied it with typescript (tsc) it works.

type StatefulSum = {
  (...nums: number[]): number;
  current: number;
  reset: (initialValue: number) => void;
};

// use the type in front of the "function" keyword.
// In case of an arrow function in front of the braces => "<FnType>() => {...}"
export const statefulSum = <StatefulSum>function (this: StatefulSum, ...nums: number[]){
    return (statefulSum.current = nums.reduce(
      (latestSum, num) => latestSum + num,
      statefulSum.current
    ));
  };

statefulSum.current = 0;
statefulSum.reset = (initialValue: number = 0) =>
  (statefulSum.current = initialValue);

Leave a Reply

Your email address will not be published. Required fields are marked *

 

GDPR Cookie Consent with Real Cookie Banner