A Short Synopsis of Types in TypeScript

A year or so ago I was working with an intern who was new to TypeScript. It made me realize that getting up to speed on syntax for types can be somewhat tricky. At the time it was hard to google for answers to basic questions (I think the age of LLMs being everywhere has mostly made this easier). I wanted a one page cheatsheet for the basics of using TypeScript to be able to point people towards.

“Go read the docs” is great advice for someone who knows what they are doing and less great if you’re lost in a sea of brand new information.

This is by no means exhaustive. The idea is that this is a quick reference for basic information. If you think there’s anything that you consider “basic” that should be here, let me know!

// Setting types for a variable:
let foo: string;
foo = "string";
// Will result in an error of: "Type 'number' is not assignable to type 'string'."
foo = 1;

const bar: number = 1;

// Define a type to be used as an argument
type ArgumentType = {
  name: string;
  anotherProperty: string;
};

// Define another type that'll be used as a return type
type TypeUsedForReturn = {
  returnString: string;
};

// Interfaces use a slightly different syntax
interface UnusedInterface {
  name: string;
  anotherProperty: string;
}

// Syntax for an arrow function with typed args and a return type
const arrowFunctionName = (argument: ArgumentType): TypeUsedForReturn => {
  const { name, anotherProperty } = argument;
  return {
    returnString: name,
  };
};

// The same as above written as a plain function declaration
function functionName(argument: ArgumentType): TypeUsedForReturn {
  const { name, anotherProperty } = argument;
  return {
    returnString: name,
  };
}

// Arrow function with destructured args and a defined return type
const arrowFunctionDestructured = ({
  name,
  anotherProperty,
}: ArgumentType): TypeUsedForReturn => {
  return {
    returnString: name,
  };
};

// The same as above written as a function declaration
function functionProperty({
  name,
  anotherProperty,
}: ArgumentType): TypeUsedForReturn {
  return {
    returnString: name,
  };
}

// Alternatively, make a type that defines args and a return type for the whole function:
type TypingAFunction = (argument: ArgumentType) => TypeUsedForReturn;
const arrowFunctionWithType: TypingAFunction = ({ name, anotherProperty }) => {
  return {
    returnString: name,
  };
};

// Use angle brackets when defining a function with a type
function functionWithType<TypingAFunction>({ name, anotherProperty }) {
  return {
    returnString: name,
  };
}

// Typing when the function does not return anything
type TypingAFunctionWithNoReturn = () => void;
const noReturn: TypingAFunctionWithNoReturn = () => {
  console.log("This space intentionally left blank");
};

// Inlining your types
const inlinedTypes = ({ name, foo }: { name: string; foo: number }) => {
  console.log("This space intentionally left blank");
};