Skip to content

Instantly share code, notes, and snippets.

@MichaelDimmitt
Last active April 3, 2025 16:16
Show Gist options
  • Save MichaelDimmitt/2374778fbbfe4083c0c6fb88e80fb75f to your computer and use it in GitHub Desktop.
Save MichaelDimmitt/2374778fbbfe4083c0c6fb88e80fb75f to your computer and use it in GitHub Desktop.
typescript guide

A typescript guide,

  1. learn the primitive types ... number, string, etc. https://www.typescriptlang.org/docs/handbook/2/everyday-types.html
  2. Unions and Intersections https://www.typescriptlang.org/docs/handbook/unions-and-intersections.html
  3. Pick, Omit, Partial https://dev.to/glebirovich/5-typescript-utility-types-that-will-make-your-life-easier-i44
  4. Typescript how to extract nested type:
    https://stackoverflow.com/questions/56779149/typescript-how-to-extract-nested-type
  5. Learn ? - also ? is not the same as | undefined - but don't focus on this too much.
  6. The "Top Level Type" is the most important type.
    Try to use the type the library gives you for free and get everything inferred from that point onward.
    If you get the Top Level Type wrong you will find that you are typing everything at a micro level and overtyping.

everything else will probably be too much early on.

Also generic types can be useful for functions and libraries that others consume; This is the simplest example of a generic I can think of:

export const func = <T>(value: T): T => {
  return value;
}
@MichaelDimmitt
Copy link
Author

MichaelDimmitt commented Apr 2, 2025

// generic type example
export const func = <T>(value: T): T & {foo: string, bar: string}  => {
  const foo = 'foo'
  const bar = 'bar'
  return {...value, foo, bar};
}

// usage:
interface Example {
  blah: string
}
const example: Example = { blah: 'test'}
const result = func<Example>(example)

/* Explanation: 
  Because you have told the func what type you will pass it
  the return type of the function is now `Example & {foo: string, bar: string}`
  so that would be the type of the result variable if we hovered over it in typescript.
*/

@MichaelDimmitt
Copy link
Author

Screenshot 2025-04-03 at 12 15 32 PM Screenshot 2025-04-03 at 12 15 48 PM

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