This content originally appeared on Bits and Pieces - Medium and was authored by berastis
Exploring the three built-in types along with their use cases, advantages, and code examples.
TypeScript is a powerful superset of JavaScript that provides static types, making it easier to write, read, and maintain code. One of the major benefits of TypeScript is its type system, which includes a variety of built-in types. In this post, we’ll explore three handy TypeScript built-in types — Partial<T>, Omit<T, U>, and Parameters<FType>. We'll go over their use cases, advantages, and provide some code examples to help you get started with them.
Partial<T>
Partial<T> is a utility type that creates a new type with all the properties of T made optional. This is useful when you want to create a new object based on an existing type, but you don't want to require all properties to be provided.
Example
Consider an interface Person with two properties name and age.
interface Person {
name: string;
age: number;
}
We want to create a function that allows updating a person’s information partially. We can use the Partial type for this.
function updatePerson(person: Person, update: Partial<Person>): Person {
return { ...person, ...update };
}
const person: Person = { name: "Alice", age: 30 };
const updatedPerson = updatePerson(person, { age: 31 });
console.log(updatedPerson); // { name: "Alice", age: 31 }
Here, we use Partial<Person> as the type for the update parameter, allowing us to provide a subset of the Person properties to update the person object.
Omit<T, U>
Omit<T, U> is another utility type that creates a new type by excluding specific properties (U) from an existing type (T). This is useful when you want to create a new object that has a similar structure to an existing one but with fewer properties.
Example
Let’s continue with our Person interface, and now we want to create a function that removes the age property.
type PersonWithoutAge = Omit<Person, "age">;
function removeAge(person: Person): PersonWithoutAge {
const { age, ...rest } = person;
return rest;
}
const personWithoutAge = removeAge(person);
console.log(personWithoutAge); // { name: "Alice" }
By using the Omit type, we can create a new PersonWithoutAge type without the age property.
Parameters<FType>
Parameters<FType> is a utility type that extracts the parameter types of a function type. This is useful when you need to obtain the parameters of a function as a tuple type.
Example
Imagine we have a function greet with the following signature:
function greet(name: string, age: number): string {
return `Hello, ${name}! You are ${age} years old.`;
}
We can use the Parameters type to obtain the parameter types of the greet function as a tuple.
type GreetParameters = Parameters<typeof greet>;
function callGreetWithArray(args: GreetParameters): string {
return greet(...args);
}
const greeting = callGreetWithArray(["Alice", 30]);
console.log(greeting); // Hello, Alice! You are 30 years old.
Here, we use Parameters<typeof greet> to extract the parameter types of the greet function and pass them as an array to another function callGreetWithArray, which then calls the original greet function with the array values.
Combining Partial<T>, Omit<T, U>, and Parameters<FType>
Let’s see an example that combines all three built-in types to create a flexible and powerful solution. We’ll create a generic apiRequest function that has the following requirements:
- Accept a configuration object that contains the necessary properties for making an API request.
- Allow users to omit certain properties when calling the function, such as the body.
- Provide a way to modify the function’s parameters easily.
interface RequestOptions {
url: string;
method: "GET" | "POST" | "PUT" | "DELETE";
headers: Record<string, string>;
body?: string;
}
function apiRequest(options: RequestOptions): Promise<Response> {
// Make the API request using the provided options.
// ...
}
// Define the type for the new function, omitting the 'body' property.
type ApiRequestWithoutBody = Omit<RequestOptions, "body">;
// Define the new function, allowing users to omit the 'body' property.
function apiRequestWithoutBody(options: ApiRequestWithoutBody): Promise<Response> {
return apiRequest(options);
}
// Extract the parameter types of the 'apiRequest' function.
type ApiRequestParameters = Parameters<typeof apiRequest>;
// Define a higher-order function that wraps the 'apiRequest' function.
function createApiRequestWrapper(wrapperFn: (params: ApiRequestParameters) => ApiRequestParameters): typeof apiRequest {
return function wrappedApiRequest(options: RequestOptions): Promise<Response> {
const modifiedParams = wrapperFn([options]);
return apiRequest(...modifiedParams);
};
}
// A wrapper function that adds an authorization header to the request.
function authWrapper(params: ApiRequestParameters): ApiRequestParameters {
const [options] = params;
return [{ ...options, headers: { ...options.headers, Authorization: "Bearer XYZ" } }];
}
// Create a new 'apiRequest' function with the authorization wrapper.
const apiRequestWithAuth = createApiRequestWrapper(authWrapper);
// Now we can make API requests with and without the 'body' property and with the authorization header.
apiRequest({ url: "/example", method: "GET", headers: {} });
apiRequestWithoutBody({ url: "/example", method: "GET", headers: {} });
apiRequestWithAuth({ url: "/example", method: "GET", headers: {} });
In this example, we used Omit<T, U> to create a new type with the body property removed, allowing us to create a new apiRequestWithoutBody function. Then, we used Parameters<FType> to extract the parameter types of the apiRequest function, enabling us to create a higher-order function createApiRequestWrapper that takes a wrapper function and modifies the function's parameters easily.
In summary, TypeScript built-in types like Partial<T>, Omit<T, U>, and Parameters<FType> offer powerful ways to create flexible, reusable, and maintainable code. By understanding and leveraging these types, you can enhance your TypeScript projects and improve your overall development experience.
💡 To further enhance your developer experience, you could use an open source toolchain like Bit which can help you share reusable types across multiple projects thereby reducing the amount of code that needs to be written, and thus cutting down development time considerably.
Learn more about it here:
Sharing Types Between Your Frontend and Backend Applications
Build Apps with reusable components, just like Lego
Bit’s open-source tool help 250,000+ devs to build apps with components.
Turn any UI, feature, or page into a reusable component — and share it across your applications. It’s easier to collaborate and build faster.
Split apps into components to make app development easier, and enjoy the best experience for the workflows you want:
→ Micro-Frontends
→ Design System
→ Code-Sharing and reuse
→ Monorepo
Learn more:
- Creating a Developer Website with Bit components
- How We Build Micro Frontends
- How we Build a Component Design System
- How to reuse React components across your projects
- 5 Ways to Build a React Monorepo
- How to Create a Composable React App with Bit
- How to Reuse and Share React Components in 2023: A Step-by-Step Guide
Mastering TypeScript’s Built-in Types: Exploring Partial<T>, Omit<T, U>, and Parameters<FType> was originally published in Bits and Pieces on Medium, where people are continuing the conversation by highlighting and responding to this story.
This content originally appeared on Bits and Pieces - Medium and was authored by berastis
berastis | Sciencx (2023-04-25T03:57:57+00:00) Mastering TypeScript’s Built-in Types: Exploring Partial<T>, Omit<T, U>, and Parameters<FType>. Retrieved from https://www.scien.cx/2023/04/25/mastering-typescripts-built-in-types-exploring-partialt-omitt-u-and-parametersftype/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.