Skip to content

Commit b9ec02a

Browse files
committed
update docusaurus
1 parent e53834c commit b9ec02a

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed

website/src/pages/index.mdx

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -135,6 +135,57 @@ const removeFirstUser = (users: ReadonlyArray<User>) => {
135135
};
136136
```
137137

138+
### Required & Optional Object Properties
139+
140+
**Strive to have majority of object properties required and use optional sparingly.**
141+
142+
It will reflect designing type-safe and maintainable code:
143+
144+
- Clarity and Predictability - Required properties make it explicit which data is always expected. This reduces ambiguity for developers using or consuming the object, as they know exactly what must be present.
145+
- Type Safety - When properties are required, TypeScript can enforce their presence at compile time. This prevents runtime errors caused by missing properties.
146+
- Avoids Overuse of Optional Chaining - If too many properties are optional, it often leads to extensive use of optional chaining (`?.`) to handle potential undefined values. This clutters the code and obscure its intent.
147+
148+
If introduction of many optional properties truly can't be avoided utilize **discriminated union type**.
149+
150+
```ts
151+
// ❌ Avoid optional properties as they increase complexity
152+
type StatusParams = {
153+
id?: number;
154+
email?: string;
155+
dashboardAccess?: boolean;
156+
adminPermissions?: ReadonlyArray<string>;
157+
subscriptionPlan?: 'free' | 'pro' | 'premium';
158+
rewardsPoints?: number;
159+
temporaryToken?: string;
160+
};
161+
162+
// ✅ Strive to have majority of properties required, if that's not possible,
163+
// use discriminated union for clear intent on object usage
164+
type AdminUser = {
165+
role: 'admin';
166+
id: number;
167+
email: string;
168+
dashboardAccess: boolean;
169+
adminPermissions: ReadonlyArray<string>;
170+
};
171+
172+
type RegularUser = {
173+
role: 'regular';
174+
id: number;
175+
email: string;
176+
subscriptionPlan: 'free' | 'pro' | 'premium';
177+
rewardsPoints: number;
178+
};
179+
180+
type GuestUser = {
181+
role: 'guest';
182+
temporaryToken: string;
183+
};
184+
185+
// Discriminating union type 'User' with no optional properties
186+
type User = AdminUser | RegularUser | GuestUser;
187+
```
188+
138189
### Discriminated union
139190

140191
If there's only one TypeScript feature to choose from, embrace discriminated unions.

0 commit comments

Comments
 (0)