types(shared): Improve LooseRequired<T> #6244
Merged
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Improve the implementation of
LooseRequired<T>
.The purpose of
LooseRequired<T>
is to change the Optional Properties in an Object Type to required, while keeping the undefined type.In the current version, LooseRequire is implemented as follows.
This implementation has problems when it encounters index signatures, consider the following code.
The result here is
{ [x: string]: any; }
This is because when the object type contains a string index signature, the
keyof T
will return string, so all other properties cannot be mappedBut TypeScript
keyof T
is a lazy value in the case of[P in keyof T]
, so we can guarantee that every property can be mapped as long as we don't expand it by usingkeof T
.To achieve the purpose of
LooseRequired<T>
, we can first set all the properties of T to required and then map the corresponding types.Here is the improved
LooseRequired<T>
:We can do a few tests
The result is :
Another example is
The result is
You can see that it avoids the attribute value merging problem caused by the keyof T being computed.