Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

background

Last time we looked at output, we documented what Partial does and how the source code implements it. After the output, I feel particularly empty, and I still feel that I need to improve the water series slowly. So how to grasp the limited fishing time and output hydrology, that is to pick a simple Utility Types to explain, so today’s protagonist is Required(change field optional to mandatory).

The body of the

The official example

Let’s take a look at the official example and the explanation

Constructs a type consisting of all properties of Type set to required. The opposite of Partial.

interfaceProps { a? :number; b? :string;
}
 
const obj: Props = { a: 5 };
 
const obj2: Required<Props> = { a: 5 }; // Property 'b' is missing in type '{ a: number; }' but required in type 'Required<Props>'.
Copy the code

The official example is so easy to understand that the truth is to read the document. The interface (Props) and the interface (Props) are both optional, but under my Required package, none of you are allowed to escape. B attribute missing, because you used Required (the pleasure of the article is to accompany the reader to read it again one word at a time)

The source code to explain

Direct source code

/** * Make all properties in T required */
type Required<T> = {
    [P inkeyof T]-? : T[P]; };Copy the code

Source code time to explain the beginning, and the last time actually almost, or the same keyof T to take the type of the field, or the same P in traversal, and have the same T[P] to obtain the type of each field, the only difference is to see a -? , but guess, is to delete optional attributes into mandatory, ha ha XDM you guessed right, this kind of operation is in TS2.8 version of the luxury package (click here to see the link), unhappy point link side of the corresponding example posted, XDM can see

/** * TypeScript 2.8 adds the ability for a mapped type to either add or remove a particular modifier. Specifically, a readonly or ? property modifier in a mapped type can now be prefixed with either + or - to indicate that the modifier should be added or removed. */ 
type MutableRequired<T> = { -readonly [P inkeyof T]-? : T[P] };// Remove readonly and ?
type ReadonlyPartial<T> = { +readonly [P inkeyof T]+? : T[P] };// Add readonly and ?
Copy the code

So this hydrology ends here, end scatter flower!

reference

  • TS Utility Types documentation – Required
  • improved-control-over-mapped-type-modifiers