Skip to content

Instantly share code, notes, and snippets.

@AnthoniG
Forked from TomProBLD/tips.ts
Created July 18, 2025 08:34
Show Gist options
  • Save AnthoniG/11917c44250c1fe87daa8adac6929fd2 to your computer and use it in GitHub Desktop.
Save AnthoniG/11917c44250c1fe87daa8adac6929fd2 to your computer and use it in GitHub Desktop.
TypeScript Tips
/**
* ---
* ---
* Partial, Pick, Omit and Required
* ---
* ---
*/
interface Props {
key1: string;
key2: number;
key3?: string;
}
// Make all properties in T optional
type PartialProps = Partial<Props>;
// From T, pick a set of properties whose keys are in the union K
type PickProps = Pick<Props, "key1" | "key3">;
// Construct a type with the properties of T except for those in type K.
type OmitProps = Omit<Props, "key3">;
// Make all properties in T required
type RequiredProps = Required<Props>;
/**
* ---
* ---
* Readonly
* ---
* ---
*/
// Make all properties in T readonly
type Amounts = Readonly<number[]>;
const amounts: Amounts = [100, 300, 500, 1000];
// ERROR: Property 'push' does not exist on type 'readonly number[]'
amounts.push(1000);
/**
* ---
* ---
* as const
* ---
* ---
*/
// Infer literal values
const COLORS = {
red: "RED",
blue: "BLUE",
green: "GREEN",
} as const;
// Some other cool stuff you can do with this -> https://www.youtube.com/watch?v=hk6ZkD0Vg3w
/**
* ---
* ---
* Index Signature
* ---
* ---
*/
enum InvoiceStatus {
Draft = "DRAFT",
Pending = "PENDING",
Paid = "PAID",
Failed = "FAILED",
}
interface InvoiceStatusByID {
// Use dynamic keys with a specific type
[id: string]: InvoiceStatus;
}
const invoiceStatusByID: InvoiceStatusByID = {
"inv-1": InvoiceStatus.Draft,
"inv-2": InvoiceStatus.Paid,
"inv-3": "Something else",
};
/**
* ---
* ---
* Literal Types
* ---
* ---
*/
type Status = "DRAFT" | "PENDING" | "PAID" | "FAILED";
// Enforce specific values for a parameter
const processInvoices = (status: Status) => {
// ... do stuff
};
processInvoices("DRAFT");
processInvoices("Something else");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment