You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
**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
+
typeStatusParams= {
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
+
typeAdminUser= {
165
+
role:'admin';
166
+
id:number;
167
+
email:string;
168
+
dashboardAccess:boolean;
169
+
adminPermissions:ReadonlyArray<string>;
170
+
};
171
+
172
+
typeRegularUser= {
173
+
role:'regular';
174
+
id:number;
175
+
email:string;
176
+
subscriptionPlan:'free'|'pro'|'premium';
177
+
rewardsPoints:number;
178
+
};
179
+
180
+
typeGuestUser= {
181
+
role:'guest';
182
+
temporaryToken:string;
183
+
};
184
+
185
+
// Discriminating union type 'User' with no optional properties
186
+
typeUser=AdminUser|RegularUser|GuestUser;
187
+
```
188
+
138
189
### Discriminated union
139
190
140
191
If there's only one TypeScript feature to choose from, embrace discriminated unions.
0 commit comments