Skip to content

Instantly share code, notes, and snippets.

@rewdy
Last active May 8, 2024 20:31
Show Gist options
  • Save rewdy/5f065ffc75cdafb469d0b2280655f813 to your computer and use it in GitHub Desktop.
Save rewdy/5f065ffc75cdafb469d0b2280655f813 to your computer and use it in GitHub Desktop.
Typescript quick reference

Typescript quick reference

When I started writing TypeScript, I didn't have much of any experience with strongly typed languages. For that reason, it was a bit of a sharp learning curve. Especially, when I was used to JS that just lets you do whatever the heck you want. This is a very basic intro that would have been helpful for me when I started. Hopefully, it's helpful to someone else out there.

Typing variables

This is generally pretty straightforward and easy to read:

const thing: string = "asdf";
const otherThing: number = 3;

Typing objects

Typing objects is also fairly easy. The only thing here to be conscious of is properties are required unless you append the ? after the key. See aliases in the example:

type User = {
  name: string;
  email: string;
  score: number;
  aliases?: string[]; // optional array of strings; can be `undefined`.
  role: "reader" | "writer" | "admin"; // union
  favoriteColor?: string; // optional
}

Typing functions

To type a function, it's just a matter of syntax. You will use (args) => return type. Peep this:

// typing
type CapitalizeFunc = (text: string) => string;

// implementation
const capitalize: CapitalizeFunc = (text) => {
  return text[0].toUpperCase() + text.slice(1);
}

// or do it inline
const capitalize2 = (text: string): string => text[0].toUpperCase() + text.slice(1);

Utility types

There are bunch of utility types built in to Typescript. These include types that make all properties of an object required, no properties required, select some properties of an object, etc. The syntax on these can be a little confusing at first (it was to me). Here are a few examples to gain your bearings:

// type with optional props
type Favorites = {
  colors?: string[];
  flavors?: string[];
  numbers?: number[];
}

type FavoritesReq = Required<Favorites>; // Note: Favorites gets passed in to Required as an arg using the <...> syntax 

// πŸ‘† is the same as πŸ‘‡
type FavoritesReq2 = {
  colors: string[];
  flavors: string[];
  numbers: number[];
}

You can do the opposite of what the Required type does with Partial. So, like this:

// this gets us back to where we started with the Favorites type
type FavoritesOpt = Partial<FavoritesReq>;

The final example I'll share is using the Pick type. This gives us the ability to create a new type with some of the properties from another type. So, let's say we want favorites with only flavors and numbers:

type FavoritesLite = Pick<Favorites, "flavors" | "numbers">; // the second arg here is a union of the keys we want

Check out all the built-in utility types here: Typescript Utility Types. (If you just 😍 lurve 😍 these and want more utility types, check out type-fest πŸŽ‰.)

Type Generics

This is sort of an advanced topic, but I think it's quite helpful to have some awareness of this early on. Typescript has "generics" which are types that receive an argument and use the type of the argument in the resulting type.

For our first example, let's say you have a function that wraps a value in an object, keeping the typing, and returns it (not necessarily a common use case, but it's easy for an example). We can maintain the typing using generics. Consider the following:

// Note how we precede the function args with the type args <...>(...) => ...
const wrapIt = <T>(incoming: T): { wrapped: T } => ({
  wrapped: incoming,
});

The above example will let T be any type. We can narrow what T can be by extending existing types. Like this:

// T can only be a string, number, or boolean
const wrapIt = <T extends string | number | boolean>(incoming: T): { wrapped: T } => ({
  wrapped: incoming,
});

There's a lot more to generics and things can get a lot more complex, but this at least gives some intro that can be helpful as you're thinking of typing your projects.

Definitely, check out the Typescript docs on Generics for a lot more details.

Bonus: stuff I often revisit

Using type predicates to filter arrays of a union type

Sometimes you have a list of items typed in some sort of union type. Often this can be a type like this:

const results: (string | undefined)[] = ["one", "two", undefined, "three"];

Often, to use this, you want to filter out the undefined items (or whatever). If you try to do this, you'll be frustrated. One good answer to this is to use type predicates. Instead of me explaining it here, check out this link with a fuller description of the problem and the answers.

πŸ‘‰ Filtering Arrays Using Type Predicates in TypeScript


That's it. Hope you like it.

Live, laugh, learn ❀️.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment