ruizb / glossary-typescript

A glossary of TypeScript.
45 stars 2 forks source link

What are Utility Types? #1

Open quangv opened 1 year ago

quangv commented 1 year ago

TypeScript provides several utility types to facilitate common type transformations.

https://www.typescriptlang.org/docs/handbook/utility-types.html#excludeuniontype-excludedmembers

To me these seems like type functions? But I don't think functions is the right word.

type T0 = Exclude<"a" | "b" | "c", "a">;
// type T0 = "b" | "c"

Is utility types the right nomenclature in TypeScript world?

Utility types = tools that transform types? type transformers?

Exclude<UnionType, ExcludedMembers>

// Constructs a type by excluding from UnionType all union members that are assignable to ExcludedMembers.

Utility types = type constructors?

ruizb commented 1 year ago

Hello 🙂

Yes, "utility type" is the right terminology as it comes directly from the official TypeScript website, per the link you shared.

Utility types are mapped types and conditional types that are defined and exposed from TypeScript itself (cf. lib.es5.d.ts). They are called "utility" because they are great at doing common operations on types.

You can define your own utility types in your projects depending on your needs, as "utility" is just a label put on top of a group of mapped and conditional types.

To me these seems like type functions? But I don't think functions is the right word.

This is actually a great way of seeing types that take other types as parameter(s). Any type that has at least 1 type parameter can be considered a "function at the type-level". But generally, these types are called "generic types" instead of "functions" or "type transformers".