This content originally appeared on Bits and Pieces - Medium and was authored by Jun Tsunokawa
A practical example of sorting an array with ‘keyof’, ‘typeof’ and enum.
I have recently implemented a sorting function in React application using object literals and TypeScript enum. In this article, I’ll explain how I implemented this with other features of TypeScript, ‘keyof’ and ‘typeof’. (The source code is available at the bottom of this article.)
💡 It’s worth adding here that if you need to reuse React components/functionalities, types or enums, you might want to consider using a component management hub such as Bit. With Bit you can easily share, discover, and reuse individual components across multiple projects.
Learn more here:
- Extracting and Reusing Pre-existing Components using bit add
- Sharing Types Between Your Frontend and Backend Applications
Goal
We’re going to sort tasks array by its priority (High to Low). The array consists of task object, which has priority key value set in it.
A usage of ‘keyof’ and ‘typeof’
Before getting into the sorting function, let’s review the basics of keyof and typeof in TyepScript.
TypeScript typeof returns a type of variable or property. If you use it with an object, it generates a type that has the same fields and types as the object.
// typeof
const a = { value: 100, text: "Test_a" } // type { value: number, text: string }
const b: typeof a = { value: 200, text: "Test_b" }
const c: typeof a = { value: 300, text: 300 } // Type 'number' is not assignable to type 'string'
The keyof operator takes an object type and produces a string or numeric literal union of its key.
// keyof
type t = keyof { value: 100, text: "Test_a" } // t = "value" | "text"
cosnt a: t = "value"
const b: t = 10 // Type '10' is not assignable to type '"value" | "text"'
If you want to make a type of an object, you need to use both keyof and typeof like below.
// keyof cannot be used with valiables
const a = { value: 100, text: "Test_a" }
type t = keyof a // 'a' refers to a value, but is being used as a type here.
type t = keyof typeof a // type t = "text" | "value"
Sorting function
With all the above in mind, let’s implement a sorting function. The array that should be sorted has a type Task[] , and priority field has a specific string defined with TaskPriority enum. To compare the elements of the array, I assigned a number to each priority status (High, Medium, Low) and make it read-only ( as const ).
export interface Task {
title: string;
priority: TaskPriority;
}
export enum TaskPriority {
LOW = "Low",
MEDIUM = "Medium",
HIGH = "High"
}
// Assign number as a flad to each priority status
const priorityOrder = { High: 1, Medium: 2, Low: 3 } as const;
// sort by High > Medium > Low
export const sortByPriority = (arr: Task[]) => {
const highToLow = (a: Task, b: Task) => {
return (
priorityOrder[a.priority as keyof typeof priorityOrder] -
priorityOrder[b.priority as keyof typeof priorityOrder]
);
};
return arr.sort(highToLow);
};
We use sort() method of the array, which can take a compare function to define how to sort the array. You can explore more about sort() method here.
Array.prototype.sort() - JavaScript | MDN
In this example, the function highToLow is the compare function that takes two arguments, {a: Task, b:Task }. It compares the number assigned to each priorityOrder key, which each argument has in priority field. If the number is smaller than the other one, it goes left (meaning smaller).
const priorityOrder = { High: 1, Medium: 2, Low: 3 } as const;
export const sortByPriority = (arr: Task[]) => {
const highToLow = (a: Task, b: Task) => {
return (
priorityOrder[a.priority as keyof typeof priorityOrder] -
priorityOrder[b.priority as keyof typeof priorityOrder]
);
};
return arr.sort(highToLow);
};
priorityOrder[a.priority as keyof typeof priorityOrder] refers to a number. The priority value in Task type and the keys of priorityOrder must have the same value and be linked together (in this context, both need to have "High" or "Medium" or "Low" as string), I used keyof tyoeof operator to define the a.priority type.
// eg) const a = { title: "test_a", priority: "High" }
// a.priority = "High"
// keyof typeof priorityOrder = "High" | "Medium" | "Low"
// priorityOrder[a.priority as keyof typeof priorityOrder] = 1
If the priorityOrder[b.priority as keyof typeof priorityOrder] is bigger than priorityOrder[a.priority as keyof typeof priorityOrder], this compare function returns a negative value, meaning the argument b is bigger than a ( a is smaller than b ). I put them in sortByPriority function, so that I can reuse them from any component.
const tasks: Task[] = [
{ title: "test1", priority: TaskPriority.MEDIUM }, // TaskPriority.MEDIUM = "Medium"
{ title: "test2", priority: TaskPriority.LOW },
{ title: "test3", priority: TaskPriority.HIGH },
{ title: "test4", priority: TaskPriority.LOW }
];
const sortedArr = sortByPriority(tasks);
console.log(sortedArr);
I have attached the source code, so please check the detail if you like.
I hope this article helps you to understand keyof typeof in TypeScript. Thank you for reading!
Build React 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
How to Use ‘keyof’ ‘typeof’ in TypeScript 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 Jun Tsunokawa
Jun Tsunokawa | Sciencx (2023-05-08T06:32:16+00:00) How to Use ‘keyof’ ‘typeof’ in TypeScript. Retrieved from https://www.scien.cx/2023/05/08/how-to-use-keyof-typeof-in-typescript/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.