Loading lesson…
type vs interface, optional fields, and structural typing. Model your data once and let every function benefit.
`interface` and `type` are almost interchangeable for object shapes. Interfaces are extendable and play nicely with classes. Type aliases handle unions, tuples, and mapped types.
interface User {
id: string;
email: string;
name?: string; // optional
readonly createdAt: Date;
}
interface AdminUser extends User {
role: "admin";
}
const u: AdminUser = {
id: "u_1",
email: "ada@example.com",
createdAt: new Date(),
role: "admin",
};
// u.createdAt = new Date(); // error: readonlyOptional fields use `?`. Readonly prevents mutation. Extends builds richer types from simpler ones.type ID = string & { readonly __brand: "ID" }; // branded nominal type
type Result<T> =
| { ok: true; value: T }
| { ok: false; error: string };
function parse(input: string): Result<number> {
const n = Number(input);
return Number.isNaN(n)
? { ok: false, error: "not a number" }
: { ok: true, value: n };
}
const r = parse("42");
if (r.ok) console.log(r.value * 2);
else console.error(r.error);Discriminated unions force you to check the tag before using the payload. Makes null checks compile-time.The big idea: model your domain with interfaces and unions. Every function you write afterward gets safety for free.
15 questions · take it digitally for instant feedback at tendril.neural-forge.io/learn/quiz/end-progx-ts-interfaces-creators
Which TypeScript feature is specifically recommended for defining object shapes that will be implemented by classes?
You need to define a type that can be exactly one of three specific string values. Which approach should you use?
What does the question mark (?) indicate when used in an interface property definition?
You want to ensure that once an object's property is set, it cannot be changed anywhere in your code. Which modifier should you use?
You have two interfaces with overlapping properties and want to combine them into one type. What approach works best?
A function receives a parameter of type 'string | number'. What values is this parameter allowed to have?
In a discriminated union, what is the 'discriminant' property used for?
What is a tuple in TypeScript?
What is structural typing in TypeScript?
You notice the exact same object shape appears in three different places in your code. What should you do?
Which statement about mapped types is true?
What advantage do interfaces provide over inline type definitions?
When modeling a domain where you have different 'kinds' of entities that share some properties but differ in others, what should you use?
Why does modeling your domain with interfaces and unions provide 'safety for free'?
What happens if you try to assign an object to a variable with an interface type, but the object is missing an optional property?