Type Inference
Working with Types

Working with Types

Type inference is a powerful feature in TypeScript that allows the compiler to deduce the types of variables based on their usage. The @ibnlanre/builder package leverages type inference to provide a seamless developer experience when working with types. This guide explores various ways to work with types in the @ibnlanre/builder package, including accessing the type of the register, and the type of nested properties.

Utility Types

TypeScript comes equipped with several utility types that can be used to manipulate and extract information from types. These utility types can be used to create new types, or to extract information from existing types. Among the most commonly used utility types are ReturnType and Parameters. These utility types are particularly useful when working with functions. You can find more utility types in the TypeScript documentation (opens in a new tab).

The following snippet demonstrates to extract types from a function:

const builder = createBuilder({
  getHeight: () => Math.random() + 150,
  setSize: async (height: number, width: number) => {
    // ...
  },
});
 
// Use the ReturnType utility to get the return type of a function.
type Height = ReturnType<typeof builder.$use.getHeight>;
//   ^? number
 
// Use the Parameter utility to get the parameter type of a function.
type Width = Parameters<typeof builder.$use.setSize>[1];
//   ^? number

Using Type Assertions

Type assertions are a way to tell the TypeScript compiler that a value has a specific type. This is useful when the compiler is unable to infer the type of a value, or when the type of a value is more specific than the compiler can determine. Type assertions can be used to assert the type of a property in a builder object.

const builder = createBuilder({
  address: {} as {
    street: string;
    city: string;
    country: string;
    house: number;
  },
});
 
// Using `as` to assert the type of a property.
type Address = typeof builder.$use.address.house;
//   ^? number