Sorting TypeScript types by required properties first

Can anyone recommend a plugin or ESLint rule that can automatically sort types by assuming required fields come first, followed by optional fields?

Here's an example before:

type TExampleSorting = {
  title?: string;
  value?: number;
  text: string;
}

And here's the desired order after sorting:

type TExampleSorting = {
  text: string; <--- required first
  title?: string;
  value?: number;
};

Is there a way to achieve this automatic sorting once the TSX file is saved?

If you have any suggestions or solutions, I would greatly appreciate it!

Answer №1

The eslint-plugin-typescript-sort-keys plugin enables you to easily sort alphabetically and make certain keys required.

To learn how to configure this plugin, visit the GitHub page - specifically check out typescript-sort-keys/interface and typescript-sort-keys/string-enum


If you are using VSCode, you have the option to enable automatic fixes upon saving your file.

Create a .vscode folder in the root of your project and add a settings.json file with the following configuration:

{
 "editor.codeActionsOnSave": {
  "source.fixAll.eslint": true
 },
 "eslint.validate": ["javascript"]
}

You can also refer to Digital Ocean's guide for a detailed explanation on enabling automatic ESLinting on save.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Playfully imitating cross-fetch

I am currently running tests on a Next/React project using Jest with Node. I have also implemented cross-fetch in my project. However, I encountered an issue when trying to mock cross-fetch for a specific component: import crossFetch from 'cross-fetc ...

Creating robust unit tests for Node.js applications with the help of redis-mock

I am facing an issue while trying to establish a connection with redis and save the data in redis using the redis-mock library in node-typescript, resulting in my test failing. Below is the code snippet for the redis connection: let client: RedisClientTyp ...

Stop the MatSort feature from activating when the space key is pressed in Angular Material

I am currently using angular material tables and have implemented filters for each column. The filter inputs are located in the row header of each column, which is working fine. However, I am facing an issue where whenever I type and press the space key, ...

Stringified HTML code showcased

When working with Angular, I have encountered an issue where I am calling a function inside an .html file that returns a string containing a table element. My goal is to convert this string into HTML code. I attempted to use [innerHtml]: <p [innerHtml ...

"The text() or json() methods in Javascript's fetch function never seem to resolve, leaving the operation in a perpetual

In my new nextjs 13 project, I'm attempting to perform a fetch operation (unsure if it's related to JavaScript or nextjs) and using console.logs to monitor the code execution. let url = `${BASE}/${module}/${path}`; url += "?" + ne ...

The term "Movie" is not compatible as a JSX component

Currently working on a movie app project but encountering issues with handling arguments and displaying them properly using TypeScript. The challenge lies in trying to map the movie object, display them individually on the homepage, and showcase all the re ...

An issue arises in TypeScript when targetting ES5 and utilizing Async Iteration, causing errors while running in the browser

After reading through the documentation on "Generation and Iteration for ES5", I implemented this polyfill: (Symbol as any).asyncIterator = Symbol.asyncIterator || Symbol.for("Symbol.asyncIterator"); However, upon doing so, my browser encountered an erro ...

When the application is converted into static files, the dynamic routes fail to function properly

I have a website that is statically exported but has dynamic routes. During development, the site works fine. However, when I build and export it, then serve the static files using serve, an issue arises. If you go to the site root and click on a link th ...

Issue with retrieving properties in Angular template due to undefined values in HTML

As a newbie to Angular, I am dedicated to improving my skills in the framework. In my project, I am utilizing three essential files: a service (Studentservice.ts) that emits an observable through the ShowBeerDetails method, and then I subscribe to this ob ...

Encountering difficulties with uploading upcoming project on a cpanel hosting due to an issue with the npm package

While attempting to upload my next project on a cpanel, I encountered an error during the installation of npm packages. npm ERR! code ERESOLVEnpm ERR! ERESOLVE unable to resolve dependency treenpm ERR! ERR! Found: <a href="/cdn-cgi/l/email-protection" c ...

Using JavaScript to place a particular tag at a designated position

I have a string that looks like this: var txtstr='<p>Text 1</p><p>&nbsp;</p><p>Text &nbsp;2</p><p>&nbsp;</p><p>Text 3&nbsp;</p>'; I have an <img src=..../> tag and ...

typescript set parameter conditionally within a function

For my upcoming app, I am working on an API that will utilize Firebase FCM Admin to send messages. Below is the code snippet: import type { NextApiRequest, NextApiResponse } from "next"; import { getMessaging } from "firebase-admin/messaging ...

The const keyword is not automatically inferred as a const when using conditional types for generic type parameters

Within Typescript, the const modifier can be applied to function type parameters. This ensures that the inferred type matches the literal received with as const. function identity<const T>(a: T){ return a } For example, when using identity({ a: 4 ...

Differentiating between model types and parameters in Prisma can greatly enhance your understanding of

Consider the following scenario: const modifyData = async(data, settings) => { await data.update(settings) } In this case, the data refers to any data source, and the settings consist of objects like where and options for updating the data. How can ...

Collaborating on code between a Typescript React application and a Typescript Express application

Struggling to find a smart way to share code between two interconnected projects? Look no further! I've got a React web app encompassing client code and an Express app serving as both the API and the React web app host. Since I use Typescript in both ...

Is there a way to check for keys in a TypeScript object that I am not familiar with?

I have a good understanding of the unknown type in TypeScript. I am dealing with untrusted input that is typed as unknown, and my goal is to verify if it contains a truthy value under the key input.things.0. function checkGreatness(input: unknown) { retu ...

The NestJs provider fails to inject and throws an error stating that this.iGalleryRepository.addImage is not a recognized function

I'm currently working on developing a NestJS TypeScript backend application that interacts with MySQL as its database, following the principles of clean architecture. My implementation includes JWT and Authorization features. However, I seem to be enc ...

Sharing a variable between an Angular component and a service

I am attempting to pass a variable from a method to a service. from calibration-detail.component.ts private heroID: number; getTheHeroID() { this.heroService.getHero(this.hero.id).subscribe(data =>(this.heroID = data.id)); } to step.service.ts I ...

Enhancing RxJS arrays of Observables with supplementary data for preservation

Question: Processing Array of Observables with Metadata in Angular How can I process an array of Observables, such as using forkJoin, while passing additional metadata for each Observable to be used in the pipe and map functions? const source = {animal: & ...

Interpolating strings in a graphQL query

Exploring the world of Gatsby and its graphQL query system for asset retrieval is a fascinating journey. I have successfully implemented a component called Image that fetches and displays images. However, I am facing a challenge in customizing the name of ...