3

5 TypeScript Concepts That Confuses New Developers

 10 months ago
source link: https://blog.bitsrc.io/5-advanced-topics-in-typescript-that-confuses-new-developers-283f8958d1e
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

5 TypeScript Concepts That Confuses New Developers

1*Us8Bo2_--zz1PNHKRvNm4A.png

TypeScript is more than just an evolution, it’s a renaissance that painted a new dawn for JavaScript developers, and bring them into the Typed Language Universe, together with C+, C#, Java. But to truly appreciate TypeScript’s brilliance, one must venture beyond its surface into the realm of its advanced offerings, where the most advanced capabilities lies.

1. Mapped Types: The Alchemist’s Tool

At the heart of TypeScript’s advanced capabilities lies the transformative power of Mapped Types which act as alchemists, morphing existing types into novel creations.

Consider a scenario where you have a UserProfile type, but you want to create a variant where all fields are optional — for instance, when updating only select fields.

type UserProfile = {
name: string;
age: number;
};

type OptionalUserProfile = Partial<UserProfile>;

Here, OptionalUserProfilemagically makes all properties optional, illustrating the adaptability of Mapped Types. Another example is Required<T>, which will on the exact opposite make all the props necessary to proceed with the validation.

On the same family there are many other (less common but still very useful) Mapped Types:

  • Readonly<T>: makes all properties of T readonly, meaning their values can’t be changed after they’re set.
  • Record<K extends keyof any, T>: constructs an object type where property keys are set to K and their values are set to T.
  • Pick<T, K extends keyof T>: constructs a type by selecting a set of properties K from T.
  • Omit<T, K extends keyof any>: constructs a type by picking all properties from T and then removing properties specified in K.
  • Exclude<T, U>: excludes from T all types that are assignable to U.
  • Extract<T, U>: constructs a type by extracting from T all types that are assignable to U.
  • NonNullable<T>: constructs a type by excluding null and undefined from T.

Is it necessary to know all of them?

I won’t suggest to dig them into your memory, however having an idea about Mapped Types would help to…


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK