Optional & Readonly Props
Part of the Introduction To TypeScript section of Coddy's JavaScript journey — lesson 41 of 73.
TypeScript provides two powerful modifiers that give you this control: the optional property modifier and the readonly modifier.
The ? symbol makes a property optional, meaning it doesn't have to be present when creating an object. This is useful for properties that might not always be needed:
interface User {
name: string;
email?: string; // Optional property
}
let user1: User = { name: "Alice" }; // Valid - email is optional
let user2: User = { name: "Bob", email: "bob@example.com" }; // Also validThe readonly modifier prevents a property from being changed after the object is created. This is perfect for properties that should remain constant, like unique identifiers:
interface Product {
readonly id: number; // Cannot be changed after creation
name: string;
}
let product: Product = { id: 1, name: "Laptop" };
product.name = "Gaming Laptop"; // Valid
// product.id = 2; // Error: Cannot assign to 'id' because it is readonlyYou can combine both modifiers on the same interface, and these modifiers work identically with both interfaces and type aliases, giving you precise control over your object structures.
Challenge
EasyCreate an interface named Book with the following properties:
titleof typestring(required)isbnof typestring(readonly)subtitleof typestring(optional)pagesof typenumber(required)publishedYearof typenumber(readonly)genreof typestring(optional)
Create an interface named Magazine with the following properties:
nameof typestring(required)issueNumberof typenumber(readonly)topicof typestring(optional)monthlySubscriptionof typeboolean(required)
Using your interfaces, create the following variables:
- Create a variable named
novelof typeBookwith title"1984", isbn"978-0-452-28423-4", pages328, and publishedYear1949 - Create a variable named
cookbookof typeBookwith title"The Joy of Cooking", isbn"978-0-7432-4626-2", subtitle"All About Baking", pages1132, publishedYear2006, and genre"Cooking" - Create a variable named
techMagof typeMagazinewith name"Tech Today", issueNumber45, and monthlySubscriptiontrue - Create a variable named
scienceMagof typeMagazinewith name"Science Weekly", issueNumber12, topic"Climate Change", and monthlySubscriptionfalse
Create a function named getBookDetails that accepts a parameter of type Book and returns a string. The function should return the book's title and pages in the format "[title] - [pages] pages".
Create a function named getMagazineInfo that accepts a parameter of type Magazine and returns a string. The function should return the magazine's name and issue number in the format "[name] Issue #[issueNumber]".
Print the following outputs on separate lines:
- Call
getBookDetailswithnoveland print the result - Call
getBookDetailswithcookbookand print the result - Call
getMagazineInfowithtechMagand print the result - Call
getMagazineInfowithscienceMagand print the result - Print the ISBN of
novel - Print the subscription status of
techMag(themonthlySubscriptionproperty)
Try it yourself
// TODO: Write your code here
// Create the Book interface
// Create the Magazine interface
// Create the variables using your interfaces
// Create the getBookDetails function
// Create the getMagazineInfo function
// Print the required outputsThis lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Introduction To TypeScript
1Getting Started with TS
What is TypeScript?Why Use TypeScript?Your First TypeScript CodeCompilation Process & ErrorsRecap: Introduction to TS4Working with Functions
Typing Params & Return ValuesTyping Arrow FunctionsThe 'void' Return TypeOptional Parameters with '?'Default Parameter ValuesTyping Rest ParametersDefining Function TypesRecap: Building Typed Funcs2Core Types
Basic Types: str, num, booleanThe 'any' Type: Escape HatchThe 'unknown' TypeWorking with 'null' & 'undef'Type Inference in ActionExplicit Type AnnotationsRecap: Core Types Practice5Types: Aliases, Unions & Inter
Type Aliases for PrimitivesUnion Types ('|')Working with Union TypesLiteral TypesIntersection Types ('&')Combining Type AliasesRecap: Advanced Type Combos3Data Structure: Arrays & Tuple
Typed Arrays'readonly' Modifier for ArraysWhat is a Tuple?Declaring and Accessing TuplesDestructuring TuplesReadonly TuplesMulti-dimensional Typed Arrays Spread Operator with ArraysRecap: Arrays and Tuples6Typing Objects and Interfaces
Inline Object Type AnnotationsType Aliases for ObjectsIntroduction to InterfacesInterfaces vs. Type AliasesOptional & Readonly PropsExtending Interfaces and TypesAdding Methods to InterfacesRecap: Defining Object Shapes