How to make our CLIs safer with types?

Rate this content
Bookmark

In this talk, we will explore the various issues encountered when building JavaScript CLIs, and demonstrate how TypeScript can address them and help us make our applications safer.

By the end of this talk, you'll understand how to abstract runtime validations type behind easy-to-use interfaces, and have all the tools you need to bring those benefits into your own CLIs at little cost - whether they are open-source projects, or internal tools.

This talk has been presented at TypeScript Congress 2023, check out the latest edition of this JavaScript Conference.

FAQ

A CLI, or Command Line Interface, is a set of words separated by space used to parameterize actions in applications. It allows users to interact with programs by typing commands into a terminal or console window.

Common problems when building CLIs include handling the correct separation of commands and options, managing variadic arguments properly, and ensuring that commands interpret options as intended rather than conflicting with other commands.

TypeScript can improve CLI safety by providing type-checking capabilities, which help in validating and ensuring that the commands and options passed are handled correctly, reducing runtime errors and bugs.

Techniques to better infer CLI option types in TypeScript include metachaining, using decorators, and a method referred to as 'the third way', which involves assigning types directly to properties, allowing TypeScript to infer types automatically.

ClipAnion is a CLI framework that utilizes TypeScript to provide type-safe command line interfaces. It supports various command structures and options, ensuring that options are correctly typed and handled within the CLI application.

The Yarn CLI moved away from Commander JS because it needed to support optional tokens and subcommands that were not natively supported by Commander JS. This led to the development of a more complex, custom solution to meet specific requirements.

Using TypeScript for internal CLI tools offers benefits such as error reduction, better code maintainability, and the ability to enforce type correctness, which can prevent many common mistakes when dealing with command line arguments and options.

Challenges with implementing decorators in TypeScript include compatibility issues between old and new decorator standards, the need for specific transpilation steps, and the inability of decorators to affect types directly, often leading to type duplication.

Maël Nison
Maël Nison
29 min
21 Sep, 2023

Comments

Sign in or register to post your comment.
Video Summary and Transcription
This talk explores the challenges of building CLIs and introduces a fully typed CLI framework built with TypeScript. It discusses the complexities and pitfalls of CLI implementation and the benefits of using decorators for metadata and logic. The talk also covers type inference challenges and presents a third way of assigning annotations as decorators. It highlights the integration of Tpanion, Zod, and ClipAnion for type checking and format validation. Finally, it mentions other CLI frameworks like ClipAllian, Common.js, and Oclif that offer similar functionality.

1. Introduction to the Talk

Short description:

Welcome to this talk about making our CLI safer with TypeScript. We will discuss the problems faced when building CLIs, techniques in TypeScript for better inference, and existing frameworks. Let's get started!

Hi everyone, and welcome to this talk about making our CLI safer with TypeScript. My name is Mayr Neonaysan. I work at Datadog as part of the front-end dev team, where we are building all sorts of tools in order to make sure our front-end engineers can be as efficient as they want to be. You can find me on Twitter and GitHub, as Arkalis, and yeah, hope to see you there.

So first, about this talk, we are going to split it into four different parts. First, we are going to talk about what are CLIs, what are the problems that we face when building them. Then we are going to see some techniques that we can use in TypeScript in order to make some better inference on the type of the options. And finally, we are going to go over some of the frameworks that already do that for us before jumping into a conclusion and recapitulating everything that we learned. Does it sound good?

2. Complexities of CLIs and Yarn CLI

Short description:

CLIs are simple and useful for parameterizing actions. However, they can be tricky, like when using npm run eslint ____ version or cp command with arguments at the beginning. Yarn CLI is one of the biggest in the JavaScript ecosystem and has specific behaviors. Commander JS was used initially, but we made run keyword and dash dash token optional, requiring additional implementation.

They are very simple to read on about and very simple to implement usually. We use them in order to parameterize actions, which can be as complicated as a full CLI application like YARN, or something much simpler like a script that you are using inside your build pipeline. The one thing they have in common is that they are typically very simple. Compared to full UI applications, they require very few boiler plates, and that makes them a very good thing to use if you are just trying to make a couple of behaviors configurable.

However, they can also be tricky. For instance, let's take npm run eslint ____ version. If you don't use the ____ token to separate the eslint and the ____ version token, you are going to end up running the version option on npm itself and not eslint. However, if you are running YARN, you don't have to do this ____ token. But in order to do that, as we are going to see later, things start to get more complicated.

The cp command looks simple. However, unlike many commands where the amount of parameters of variadic arguments is at the end of the command, in the case of cp, it's at the beginning of the command. You have slc1, slc2, any number of other sources, but you must have one destination at the end. So the required position of arguments is at the end rather than the beginning. You have the arm command that has the preserve-root option, but it also has the "-no-preserve-root option". And if you're implementing something like this in your scripts, you usually want to declare both options into one, so that you don't have to duplicate them. And finally, let's take the case of the vlc-v. If you look at this command and you don't know anything else about it, you would think that "-v", is actually a boolean flag. But it's not. If you run vlc-vvv, you will not get the same behavior as if you were running vlc-v. Because vvv is actually a counter. It counts the number of times that you're passing it to the command.

Now, let's talk about the Yarn CLI itself. It's very interesting, because the Yarn CLI is one of the biggest CLI interfaces that we all use in the JavaScript ecosystem. Each has more than twenty commands, and each of them accepts options, and we have some very specific behaviors like we previously saw. At first, it started to use Commander JS, which is a CLI framework for JavaScript that supports subcommands, and that's something that is very important for Yarn, because Yarn add, Yarn remove, Yarn upgrade to interact with you, all those kind of things are commands from the main application. However, we decided to eventually make the run keyword optional, so that you could run Yarn eslint instead of Yarn run-eslint, and that wasn't something that Commander JS actually supported out of the box. So we had to implement our own code in order to support that. Then, later on, we decided to also make the dash dash token optional, so that if you run Yarn eslint dash dash version, then the dash dash version is applied on eslint and not on Yarn itself. That's super handy. However, it required to implement something else on top of Commander JS.

Check out more articles and videos

We constantly think of articles and videos that might spark Git people interest / skill us up or help building a stellar career

React's Most Useful Types
React Day Berlin 2023React Day Berlin 2023
21 min
React's Most Useful Types
Top Content
Watch video: React's Most Useful Types
Today's Talk focuses on React's best types and JSX. It covers the types of JSX and React components, including React.fc and React.reactnode. The discussion also explores JSX intrinsic elements and react.component props, highlighting their differences and use cases. The Talk concludes with insights on using React.componentType and passing components, as well as utilizing the react.element ref type for external libraries like React-Select.
TypeScript and React: Secrets of a Happy Marriage
React Advanced 2022React Advanced 2022
21 min
TypeScript and React: Secrets of a Happy Marriage
Top Content
React and TypeScript have a strong relationship, with TypeScript offering benefits like better type checking and contract enforcement. Failing early and failing hard is important in software development to catch errors and debug effectively. TypeScript provides early detection of errors and ensures data accuracy in components and hooks. It offers superior type safety but can become complex as the codebase grows. Using union types in props can resolve errors and address dependencies. Dynamic communication and type contracts can be achieved through generics. Understanding React's built-in types and hooks like useState and useRef is crucial for leveraging their functionality.
Making Magic: Building a TypeScript-First Framework
TypeScript Congress 2023TypeScript Congress 2023
31 min
Making Magic: Building a TypeScript-First Framework
Top Content
Daniel Rowe discusses building a TypeScript-first framework at TypeScript Congress and shares his involvement in various projects. Nuxt is a progressive framework built on Vue.js, aiming to reduce friction and distraction for developers. It leverages TypeScript for inference and aims to be the source of truth for projects. Nuxt provides type safety and extensibility through integration with TypeScript. Migrating to TypeScript offers long-term maintenance benefits and can uncover hidden bugs. Nuxt focuses on improving existing tools and finds inspiration in frameworks like TRPC.
Stop Writing Your Routes
Vue.js London 2023Vue.js London 2023
30 min
Stop Writing Your Routes
Designing APIs is a challenge, and it's important to consider the language used and different versions of the API. API ergonomics focus on ease of use and trade-offs. Routing is a misunderstood aspect of API design, and file-based routing can simplify it. Unplugging View Router provides typed routes and eliminates the need to pass routes when creating the router. Data loading and handling can be improved with data loaders and predictable routes. Handling protected routes and index and ID files are also discussed.
Faster TypeScript builds with --isolatedDeclarations
TypeScript Congress 2023TypeScript Congress 2023
24 min
Faster TypeScript builds with --isolatedDeclarations
Top Content
This talk discusses the performance issues in TypeScript builds and introduces a new feature called isolated declarations. By running the compiler in parallel and using isolated modules, significant performance gains can be achieved. Isolated declarations improve build speed, compatibility with other tools, and require developers to write types in code. This feature has the potential to further increase performance and may be available in TypeScript soon.
Full-stack & typesafe React (+Native) apps with tRPC.io
React Advanced 2021React Advanced 2021
6 min
Full-stack & typesafe React (+Native) apps with tRPC.io
Top Content
Alex introduces tRPC, a toolkit for making end-to-end type-safe APIs easily, with auto-completion of API endpoints and inferred data from backend to frontend. tRPC works the same way in React Native and can be adopted incrementally. The example showcases backend communication with a database using queries and validators, with types inferred to the frontend and data retrieval done using Prisma ORM.

Workshops on related topic

React, TypeScript, and TDD
React Advanced 2021React Advanced 2021
174 min
React, TypeScript, and TDD
Top Content
Featured WorkshopFree
Paul Everitt
Paul Everitt
ReactJS is wildly popular and thus wildly supported. TypeScript is increasingly popular, and thus increasingly supported.

The two together? Not as much. Given that they both change quickly, it's hard to find accurate learning materials.

React+TypeScript, with JetBrains IDEs? That three-part combination is the topic of this series. We'll show a little about a lot. Meaning, the key steps to getting productive, in the IDE, for React projects using TypeScript. Along the way we'll show test-driven development and emphasize tips-and-tricks in the IDE.
Mastering advanced concepts in TypeScript
React Summit US 2023React Summit US 2023
132 min
Mastering advanced concepts in TypeScript
Top Content
Featured WorkshopFree
Jiri Lojda
Jiri Lojda
TypeScript is not just types and interfaces. Join this workshop to master more advanced features of TypeScript that will make your code bullet-proof. We will cover conditional types and infer notation, template strings and how to map over union types and object/array properties. Each topic will be demonstrated on a sample application that was written with basic types or no types at all and we will together improve the code so you get more familiar with each feature and can bring this new knowledge directly into your projects.
You will learn:- - What are conditional types and infer notation- What are template strings- How to map over union types and object/array properties.
Deep TypeScript Tips & Tricks
Node Congress 2024Node Congress 2024
83 min
Deep TypeScript Tips & Tricks
Top Content
Featured Workshop
Josh Goldberg
Josh Goldberg
TypeScript has a powerful type system with all sorts of fancy features for representing wild and wacky JavaScript states. But the syntax to do so isn't always straightforward, and the error messages aren't always precise in telling you what's wrong. Let's dive into how many of TypeScript's more powerful features really work, what kinds of real-world problems they solve, and how to wrestle the type system into submission so you can write truly excellent TypeScript code.
Best Practices and Advanced TypeScript Tips for React Developers
React Advanced 2022React Advanced 2022
148 min
Best Practices and Advanced TypeScript Tips for React Developers
Top Content
Featured Workshop
Maurice de Beijer
Maurice de Beijer
Are you a React developer trying to get the most benefits from TypeScript? Then this is the workshop for you.In this interactive workshop, we will start at the basics and examine the pros and cons of different ways you can declare React components using TypeScript. After that we will move to more advanced concepts where we will go beyond the strict setting of TypeScript. You will learn when to use types like any, unknown and never. We will explore the use of type predicates, guards and exhaustive checking. You will learn about the built-in mapped types as well as how to create your own new type map utilities. And we will start programming in the TypeScript type system using conditional types and type inferring.
Building Your Own Custom Type System
React Summit 2024React Summit 2024
38 min
Building Your Own Custom Type System
Featured Workshop
Kunal Dubey
Kunal Dubey
I'll introduce the audience to a concept where they can have end-to-end type systems that helps ensure typesafety across the teams Such a system not only improves communication between teams but also helps teams collaborate effectively and ship way faster than they used to before. By having a custom type system, teams can also identify the errors and modify the API contracts on their IDE, which contributes to a better Developer Experience. The workshop would primarily leverage TS to showcase the concept and use tools like OpenAPI to generate the typesystem on the client side. 
Frictionless Development With Unified Type System
JSNation 2024JSNation 2024
113 min
Frictionless Development With Unified Type System
Featured Workshop
Ejiro Asiuwhu
Ejiro Asiuwhu
Imagine developing where frontend and backend sing in harmony, types dance in perfect sync, and errors become a distant memory. That's the magic of TypeScript Nirvana!
Join me on a journey to unveil the secrets of unified type definitions, the key to unlocking frictionless development. We'll dive into:
- Shared language, shared love: Define types once, share them everywhere. Consistency becomes your BFF, errors your worst nightmare (one you'll rarely see).- Effortless coding: Ditch the manual grind of type checking. TypeScript's got your back, freeing you to focus on building awesomeness.- Maintainability magic: With crystal-clear types guiding your code, maintaining it becomes a walk in the park. More time innovating, less time debugging.- Security fortress: TypeScript's type system shields your app from common vulnerabilities, making it a fortress against security threats.