Types, interfaces & type inference
Type functions, objects and API responses without overusing any.
By Invicly Tech, , in Frontend with React & Next.js. About 11 minutes to read.
In short
TypeScript adds types to JavaScript and checks them before your code runs. It catches typos, missing fields and wrong arguments in the editor, then compiles to plain JavaScript.
Explained simply
JavaScript lets you pass anything anywhere. If a function expects a user object and you pass a number, you only find out when the code runs, often in front of a real user. TypeScript adds a checker that reads your code first and warns you in the editor, before anything runs.
A type is a description of what a value looks like. string, number and boolean are simple types. An object type lists the fields and their types, for example a user has an id that is a number and a name that is a string.
You do not have to write types everywhere. TypeScript can often work them out by itself, which is called inference. If you write const count = 3, it already knows count is a number. You mostly add types to function inputs and to shared data shapes.
The most important thing to remember: types disappear when the code is compiled. They help you while writing, but they cannot stop a server from sending bad data. For data that comes from outside your program, you still need a runtime check.
Press Play on a diagram to walk through it one step at a time.
- Step 1Write .ts code
Add annotations where inference is not enough
- Step 2Type check
The compiler reports mismatches in the editor and CI
- Step 3Strip types
Types are removed; only JavaScript remains
- Step 4Run JavaScript
Browsers and Node run the output, with no runtime checks
- Primitives
- string, number, boolean
- bigint, symbol
- null, undefined
- Objects
- interface or type shapes
- Arrays: string[]
- Tuples: [number, number]
- Functions
- (a: number) => string
- void for no return value
- Literals
- "dark" | "light"
- Made with const or as const
- Escape hatches
- any: no checking
- unknown: check before use
- never: cannot happen
In depth
Structural typing: shape beats name
TypeScript compares types by their shape, not by their name. If a function wants a value with id: number and name: string, any object that has at least those two fields is accepted, even if it was never declared as that type. This is called structural typing, and it matches how JavaScript objects really behave.
There is one extra safety net. When you pass an object literal directly, written inline in the call, TypeScript runs an excess property check and complains about fields the type does not know. That is how it catches typos like timeoutMS instead of timeoutMs. If you first store the object in a variable and then pass the variable, the extra fields are allowed, because the object might be used elsewhere.
- Extra fields are fine for variables
- Extra fields are an error for inline object literals
- Missing required fields are always an error
interface or type?
Both can describe an object shape, and for most code the choice does not matter. The differences are small but real. An interface can be declared twice and the two declarations merge, which libraries use to let you add fields to their types. An interface extends another with the extends keyword and gives clear error messages.
A type alias can name anything: a union like "admin" | "user", a tuple, a function type, or a mapped type. Only type can do unions. A common team rule is: use interface for object shapes that others may extend, and type for everything else. Pick one rule and stay consistent.
- Object shapes only
- Can be declared again and merged
- Extends with the extends keyword
- Good for public object APIs
- Any type: unions, tuples, functions
- Cannot be reopened once declared
- Combines with & (intersection)
- Needed for unions and mapped types
Where inference works and where to annotate
Inference is strong for local variables and return values. const total = price * qty is a number without help. Return types are inferred from the return statements.
Annotate function parameters: TypeScript cannot guess what callers will pass, and with strict mode an unannotated parameter is an error. Annotate exported functions and public APIs too, so a change inside the function cannot silently change the type other files depend on.
Watch out for widening. let mode = "dark" is typed as string, because a let can change. const mode = "dark" is the literal type "dark". Adding as const to an object or array keeps every value as a readonly literal, which is handy for config lists and route names.
- Parameters: always annotate
- Locals: let inference work
- Exported functions: annotate the return type
- Empty arrays: annotate, for example const ids: number[] = []
Typing API responses without any
res.json() returns any, so whatever you assign it to is accepted without checks. Writing as User only tells the compiler to trust you; it checks nothing. If the server renames a field, your code still compiles and breaks at runtime.
The safe pattern is to treat outside data as unknown, then validate it. unknown forces you to check before use. A schema library like Zod does the checking for you: you describe the shape once, call parse on the data, and get back a fully typed value or a clear error. z.infer gives you the TypeScript type from the same schema, so the type and the runtime check can never drift apart.
- Step 1fetch()
The body is just bytes from the network
- Step 2res.json()
Store it as unknown, not any
- Step 3Schema.parse()
Checks every field at runtime
- Step 4Typed value
Safe to use; bad data throws early
Arrays, tuples, optional and readonly
An array of strings is written string[]. A tuple is a fixed-length array where each position has its own type, like [number, number] for a point. React's useState returns a tuple, which is why you can destructure it.
A question mark makes a field optional: email?: string means the field may be missing, so its type is string | undefined. readonly stops reassignment of a field, and readonly string[] removes push and splice. These are compile-time only; nothing freezes the object at runtime. Use them to document intent and to stop accidental mutation of shared data, such as React state.
Learn it in 4 short steps
About 1h each. Track them with a timer in your plan.
- 1Annotate primitives, arrays and objects~1h
- 2Define interfaces and type aliases~1h
- 3Rely on type inference sensibly~1h
- 4Type API responses without any~1h
Key points
- Types exist only at compile time; they do not validate data at runtime.
- Let inference type local variables; annotate function parameters and public APIs.
- Use interface or type to describe object shapes.
- Prefer unknown over any for untrusted data, then narrow or validate it.
Key terms
Tap a card to flip it. 0/6 known
Examples
interface User {
id: number;
name: string;
email?: string;
}
function greet(user: User): string {
return `Hi, ${user.name}`;
}
async function getUser(id: number): Promise<User> {
const res = await fetch(`/api/users/${id}`);
return (await res.json()) as User;
}An interface and typed function parameters and return types.
Loading products with a schema
A product page loads JSON from an API. Step 1: describe the product once with Zod. Step 2: get the TypeScript type from the schema with z.infer, so you never write it twice. Step 3: store the JSON as unknown. Step 4: parse it. If the server sends price as a string by mistake, parse throws a clear error right here, not deep inside a component later.
import { z } from "zod";
const Product = z.object({
id: z.number(),
name: z.string(),
price: z.number(),
tags: z.array(z.string()).default([]),
});
type Product = z.infer<typeof Product>;
export async function getProducts(): Promise<Product[]> {
const res = await fetch("/api/products");
if (!res.ok) throw new Error("HTTP " + res.status);
const data: unknown = await res.json();
return z.array(Product).parse(data);
}Why one typo is caught and the other is not
Step 1: call load with an inline object that has a typo. TypeScript runs the excess property check and even suggests the right name. Step 2: put the same object in a variable first and pass that. Now there is no error, because structural typing allows extra fields, and timeoutMs is optional. Lesson: pass options inline, or annotate the variable with the type so the check runs at the assignment.
interface Options {
retries: number;
timeoutMs?: number;
}
function load(url: string, opts: Options) {
console.log(url, opts.retries);
}
load("/api", { retries: 3, timeoutMS: 500 });
// Error: 'timeoutMS' does not exist in type 'Options'.
const opts = { retries: 3, timeoutMS: 500 };
load("/api", opts); // no error: the typo slips through
const safe: Options = { retries: 3, timeoutMS: 500 }; // error againQuick reference
- Annotate parameters and exported functions; let inference handle locals
- let x = "a" is string; const x = "a" is the literal type "a"
- Use unknown for outside data, then validate or narrow it before use
- as Type only silences the checker; it never converts or checks data
- email?: string means the field may be missing (string | undefined)
- Only type aliases can name unions like "admin" | "user"
- as const keeps literal values and makes arrays and objects readonly
- Types are erased at build time and add zero runtime cost
Common mistakes
- Casting API responses with as and assuming the server really matches the type.
- Sprinkling any to silence errors instead of fixing the types.
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
Write formatPrice(cents, currency) that returns a string like "$12.50". currency is optional and defaults to "USD". Add types to the parameters and the return value.
- Exercise 2medium
Model a blog Post with a readonly id, title, body, an optional list of tags and an author object with name and optional avatarUrl. Write a function that returns the post's tags or an empty array.
- Exercise 3hard
Fetch /api/users, validate that it is an array of { id: number; email: string } with Zod, and return the typed array. If validation fails, log which fields were wrong and return an empty array.
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- Should I use interface or type in TypeScript?
- Either works for object shapes. Many teams use interface for objects and type for unions and everything else; consistency matters more than the choice.
- Does TypeScript make my app slower?
- No. Types are removed at build time, so the JavaScript that runs is the same speed. The only cost is the type-checking step during development and CI.
- Is it ever OK to use any?
- Rarely, for example while migrating old JavaScript. Prefer unknown, which keeps safety by forcing a check before use.
- Can browsers run TypeScript directly?
- No. A compiler or bundler strips the types first. Recent Node.js versions can strip types from .ts files on the fly, but they still do not type check them.