Issue
interface I1 {
x: number;
y: string;
}
interface I2 {
x?: number;
y?: string;
}
const tmp1: Partial<I1> = {}, tmp2: I2 = {};
Just like the example, is there an obvious difference between these two things?
Solution
The difference is what is being expressed.
The types of tmp1 and tmp2 are the same because Partial does the same as
type MyPartial<T> = { [K in keyof T]+?: T[K] }
Where +? is a mapping modifier that makes a property optional.
However, other than structural compatibility, the types express different things:
I1implies that the regular shape of the object expected is non-optional. Modifying it viaPartialmeans that is an exception to the regular expectations.I2is the opposite - the regular shape of the object expected is fully optional.
Illustrating with a real looking type might make it be clearer:
interface User {
age: number;
name: string;
}
Cements the decision that all User objects must have age and name filled in. Otherwise they are not a valid User. However, conceivably there can be a Partial<User> in the system while the full set of information is still being collected. That would be a temporary state cannot be directly used with (for example)
function saveUser(user: User) { /* ... */ }
as that function requires a real user object with all the fields.
Conversely, a fully optional type might be more appropriate when any subset of the data is valid:
interface SurveyResult {
score?: number;
comment?: string;
}
Means that any survey outcome is expected. Only the score can be filled in, or the comment, or even nothing. Presumably, even an empty result still counts for the total surveys or similar.
Answered By - VLAZ
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.