An open API service indexing awesome lists of open source software.

https://github.com/AllThingsSmitty/typescript-tips-everyone-should-know

A curated collection of practical TypeScript patterns that improve safety, readability, maintainability, and developer experience.
https://github.com/AllThingsSmitty/typescript-tips-everyone-should-know

best-practices clean-code code-quality developer-experience front-end frontend generics javascript maintainability runtime-validation static-analysis type-safety typescript

Last synced: 1 day ago
JSON representation

A curated collection of practical TypeScript patterns that improve safety, readability, maintainability, and developer experience.

Awesome Lists containing this project

README

          

# TypeScript Tips Everyone Should Know

A curated collection of practical TypeScript patterns that improve safety, readability, maintainability, and developer experience.

Most of these are small individually. Together, they dramatically change how TypeScript code feels to work in.

## Table of Contents

1. [Prefer `unknown` Over `any`](#prefer-unknown-over-any)
2. [Let Type Inference Do the Work](#let-type-inference-do-the-work)
3. [Prefer `satisfies` Over `as`](#prefer-satisfies-over-as)
4. [Derive Types From Values](#derive-types-from-values-instead-of-duplicating-them)
5. [Make Invalid States Impossible to Represent](#make-invalid-states-impossible-to-represent)
6. [Use Exhaustive Checks With `never`](#use-exhaustive-checks-with-never)
7. [Use `as const` for Constants](#use-as-const-for-configuration-and-constants)
8. [Use Type Predicates](#use-type-predicates-for-reusable-narrowing)
9. [Build Types From Existing Types](#build-new-types-from-existing-types)
10. [Validate External Data at Runtime](#validate-external-data-at-runtime)
11. [Avoid `enum` in Most Cases](#avoid-enum-in-most-cases)
12. [Prefer Inferable Generics](#prefer-generics-that-infer-automatically)
13. [Enable Strict Compiler Options](#turn-on-the-strict-compiler-options)
14. [Learn Template Literal Types](#learn-template-literal-types)
15. [Type Safety ≠ Runtime Safety](#type-safe-does-not-mean-runtime-safe)

### Prefer `unknown` Over `any`

A lot of type safety starts here.

`unknown` forces you to prove what a value is before using it. `any` skips the type system entirely, allowing unsafe operations to spread through your code.

```ts
function parse(data: unknown) {
if (typeof data === "string") {
return data.toUpperCase();
}
}
```

#### Why it matters

- Forces validation before use
- Preserves type safety
- Prevents unsafe type leakage

[Table of Contents](#table-of-contents)

### Let Type Inference Do the Work

The best TypeScript code often relies on inference instead of repeating information the compiler already knows.

```ts
const name = "Ada";
```

Instead of:

```ts
const name: string = "Ada";
```

#### Over-annotation

- Widens types
- Hurts inference
- Creates maintenance overhead

Inference tends to scale better than annotation.

[Table of Contents](#table-of-contents)

### Prefer `satisfies` Over `as`

One of the most important modern TypeScript features.

```ts
const routes = {
home: "/",
about: "/about",
} satisfies Record;
```

Instead of:

```ts
const routes = {
home: "/",
about: "/about",
} as Record;
```

`satisfies` checks that a value matches a type while preserving its inferred type.

Use `satisfies` when validating object shapes. Reserve `as` for cases where you're expressing information the compiler genuinely can't infer.

[Table of Contents](#table-of-contents)

### Derive Types From Values Instead of Duplicating Them

One of the biggest TypeScript mindset shifts.

```ts
const roles = ["admin", "user", "guest"] as const;

type Role = (typeof roles)[number];
```

This creates a single source of truth. If the runtime values change, the type updates automatically, eliminating duplication and preventing the two from drifting apart.

[Table of Contents](#table-of-contents)

### Make Invalid States Impossible to Represent

Good TypeScript models don't just describe data, they prevent impossible combinations from existing in the first place.

Discriminated unions are one of the most effective ways to model these constraints.

```ts
type State =
| { status: "loading" }
| { status: "success"; data: User }
| { status: "error"; error: Error };
```

These models scale much better than loose optional property blobs because invalid states simply can't be represented.

Future refactors become safer because the compiler ensures every valid state is handled.

[Table of Contents](#table-of-contents)

### Use Exhaustive Checks With `never`

Once you've modeled your states as a discriminated union, exhaustiveness checking ensures every case is handled.

```ts
default: {
const exhaustive: never = state;
return exhaustive;
}
```

Add a new state, and the compiler immediately points out every place that needs updating.

[Table of Contents](#table-of-contents)

### Use `as const` for Configuration and Constants

Without `as const`:

```ts
const theme = {
mode: "dark",
};
```

`mode` becomes `string`.

With `as const`:

```ts
const theme = {
mode: "dark",
} as const;
```

Now it becomes `'dark'`.

A small feature that dramatically improves inference for configuration objects and constants.

[Table of Contents](#table-of-contents)

### Use Type Predicates for Reusable Narrowing

Connect runtime checks to compile-time intelligence.

```ts
function isUser(value: unknown): value is User {
return typeof value === "object" && value !== null && "id" in value;
}
```

Then:

```ts
if (isUser(data)) {
data.id;
}
```

This becomes especially useful around APIs and external input boundaries.

[Table of Contents](#table-of-contents)

### Build New Types From Existing Types

Think in transformations instead of duplication.

```ts
type UserPreview = Pick;
```

### Learn these utility types

- `Pick`
- `Omit`
- `Partial`
- `Required`
- Indexed access types

These utilities become much more valuable as applications grow.

[Table of Contents](#table-of-contents)

### Validate External Data at Runtime

TypeScript does **not** validate API responses.

This is one of the most misunderstood parts of TypeScript.

```ts
const UserSchema = z.object({
id: z.string(),
name: z.string(),
});
```

Every API response, form submission, environment variable, JSON file, and user input is an untrusted boundary.

TypeScript can't validate external data; you need runtime validation for that.

[Table of Contents](#table-of-contents)

### Avoid `enum` in Most Cases

Usually simpler:

```ts
const roles = ["admin", "user"] as const;
```

Than:

```ts
enum Role {
Admin,
User,
}
```

In most application code, literal unions are easier to refactor, serialize, and reason about than enums.

Enums still have valid use cases, but they're often unnecessary.

[Table of Contents](#table-of-contents)

### Prefer Generics That Infer Automatically

Great TypeScript APIs rarely require manual generic arguments.

Less ideal:

```ts
getData();
```

Better:

```ts
getData(userSchema);
```

Inference usually scales better than annotation-heavy APIs.

[Table of Contents](#table-of-contents)

### Turn On the Strict Compiler Options

Many teams use TypeScript in "autocomplete mode."

Strict mode is where TypeScript really starts paying off.

```json
{
"strict": true,
"useUnknownInCatchVariables": true,
"noUncheckedIndexedAccess": true,
"exactOptionalPropertyTypes": true
}
```

These flags dramatically improve correctness.

[Table of Contents](#table-of-contents)

### Learn Template Literal Types

One of the most powerful modern TypeScript features.

```ts
type Route = `/api/${string}`;
```

Excellent for:

- Routes
- Event names
- CSS utilities
- Design systems
- Query keys

Once you start using them, they show up everywhere.

[Table of Contents](#table-of-contents)

### "Type-Safe" Does Not Mean "Runtime Safe"

A perfect final tip because it reframes everything.

This compiles:

```ts
const user = (await response.json()) as User;
```

But it may still fail at runtime.

TypeScript improves correctness, but it isn't a runtime safety net.

- It does not validate external data
- It does not guarantee good architecture
- It does not eliminate runtime bugs

Use TypeScript to model your program well. Then validate anything that comes from the outside world.

[Table of Contents](#table-of-contents)