Utility Type (+MappedType)



1. Record

Maps all keys to the specified type (it is a mapped type)

So you can't have either home or about missing

type Page = "home" | "about";
type PageInfo = { title: string };

const nav: Record<Page, PageInfo> = {
  home: { title: "Title1" },
  about: { title: "Title2" },
};

The above example is the same as the mapped type example below

(we use in because it is a mapped type )

const nav: { [key in Page]:PageInfo } = {
  home: { title: "Title1" },
  about: { title: "Title2" },
};

What is a MappedType:

- MappedType : Mainly used to generate key-value pairs based on each member by traversing the members of a union type

in, etc.

Includes all key values and is required

type MappedType = { [Key in UnionType]: Type };




2. Required

Changes all properties to required.

type PartialType = { name?: string };
type RequiredType = Required<PartialType>;

const obj: RequiredType = { name: "John" }; // `name` required


3. Partial

Selectively change all properties.

type FullType = { name: string; age: number };
type PartialType = Partial<FullType>;

const obj: PartialType = { name: "John" }; // `age` can be omitted


4. Readonly

Changes all properties to read-only.

type MutableType = { name: string };
type ReadonlyType = Readonly<MutableType>;

const obj: ReadonlyType = { name: "John" };
// obj.name = "Doe"; // error occurred


5. Pick

Extract only certain properties.

type FullType = { name: string; age: number };
type NameOnly = Pick<FullType, "name">;

const obj: NameOnly = { name: "John" };


6. Omit

Exclude a specific property.

type FullType = { name: string; age: number };
type WithoutAge = Omit<FullType, "age">;

const obj: WithoutAge = { name: "John" };


7. Extract

Extract a specific type from a union type.

type Mixed = "a" | "b" | "c";
type OnlyA = Extract<Mixed, "a" | "d">; // "a"


8. Exclude

Removing a specific type from a union type.

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


9. NonNullable

null and undefined removed.

type MaybeNull = string | null | undefined;
type NotNull = NonNullable<MaybeNull>; // string


10. Nullable (user-defined)

null and undefined added.

Nullable is not defined in Typescript's utility types, but it can be implemented using generics as shown below

type Nullable<T> = T | null | undefined;
type Example = Nullable<string>; // string | null | undefined


11. Parameters

Extract function parameter types into a tuple.

type Fn = (a: string, b: number) => void;
type Params = Parameters<Fn>; // [string, number]


12. ReturnType

Extract function return type.

type Fn = () => string;
type Ret = ReturnType<Fn>; // string


13. InstanceType

Extracting the constructor type of a class.

class MyClass {
  name: string = "John";
}
type Instance = InstanceType<typeof MyClass>; // MyClass





References

UtilityType Handbook





Nov 16, 2024 Views 42