Last updated
TypeScript 101: What is it and why should you use it?
You’ve probably heard about TypeScript, a well-loved tool popular among professional web developers. However, going from name familiarity to a basic understanding of TypeScript's functionality is harder than it seems. TypeScript's relationship to JavaScript and the broader world of web development is not immediately apparent.
In brief, TypeScript is a type-safe superset of JavaScript, turning the dynamically-typed JS into a statically-typed language. In other words, it’s a particular version of JavaScript with powerful extra features that improve the quality of your code. Importantly, you can choose where and when to use those features–and if you want to write plain JavaScript, that's fine too.
Chief among these extra features is increased error messages in the development environment. More error messages? Who needs that? For starters, anyone who wants to dramatically reduce the number of bugs they encounter in their project.
By defining the types of data assigned to memory in code, TypeScript will trigger errors whenever an incorrect type is assigned. This makes code safer and more maintainable. So while
let days = 6
days = "Robert"
is acceptable in vanilla JavaScript, in TypeScript it would trigger an error message. days
's original data type is that of a number (6), while its new value's data type is a string ("Robert"). Pointing out this discrepancy early in the development process can prevent costly errors. For instance, if your program scheduled someone's appointment "Robert" days from now, you will surely have a problem. That's why TypeScript ensures you write "type-safe" code.
Projects with TypeScript are often faster to develop and easier to integrate with frameworks and packages. While TS takes time to learn and set up in a project, many developers swear by it. In fact, TypeScript was ranked the third most-loved programming language in the StackOverflow 2021 Developer Survey.
Let's explore what TypeScript can do for developers.
As we mentioned above, TypeScript enables you to write better code by surfacing problems much earlier than in standard JavaScript. In JS, you can’t see errors caused by incorrect types until the code reaches production. But in TS, you’ll see the problem at the time of authoring. By surfacing type errors in development instead of production, TypeScript saves developers time and reduces headaches.
Working with type definitions for frameworks and libraries is programming with cruise control. Instead of tabbing to a browser to look up documentation after writing every line of code, TypeScript enables much smarter Intellisense features to autocomplete your code as you write it.
This is a life-saver when working with large codebases or frameworks like Nest.js, for which you have to keep track of countless methods, classes, and variables. It's easy to forget the syntax of such a complex codebase or framework, but TypeScript remembers it for you.
One of TypeScript’s best features is that it saves time by generating the docs for your project as you write it. Because the TypeScript codebase's types are defined so painstakingly, those definitions are a great way to explain how the code should be used. When used with a library generator like TypeDoc, TypeScript can output beautiful documentation that would otherwise be a huge pain to write by hand.
At Sanity, we use TypeScript to build the Sanity Studio. For us, TypeScript brings many benefits that align with our goals of providing excellent developer experience.
TypeScript’s typing system empowers us to provide you with enhanced tooling support, including features like autocomplete and validation of the Studio configuration. Moreover, TypeScript allows us to effectively communicate API stability using TS Doc annotations, enabling you to make well-informed decisions when customizing the Studio.
Assuming you've got Node.js installed, install TypeScript globally with npm
using:
npm install -g typescript
Then to compile TypeScript to JavaScript, you can run tsc (tsc is short for TypeScript compiler).
The first time you set up TypeScript in a project, though, you should define your preferred settings in the default TypeScript configuration file, tsconfig.json, which you can generate by running:
tsc --init
in the project root.
Now, when it's time to compile your TypeScript to JavaScript, you simply run the TS Compiler and it'll output JS according to your specifications in the tsconfig.json. Do so by running
tsc
in the root of the project folder. It'll output to a file specified in the tsconfig file.
Learn more about how to configure the tsconfig.json in the TypeScript docs.
Developers love TypeScript for the productivity boost it gives to large projects. In fact, TS can integrate with most JS frameworks used for large projects today. Here are some frameworks that are particularly well-suited to TypeScript development.
Some frameworks have TypeScript baked into the project from day one. This saves time on configuration and makes for a more comfortable experience for TypeScript developers.
Nest.js is a server-side framework that is quickly becoming one of the most popular ways to write scalable, testable Node.js APIs. It is written in a highly opinionated structure that uses TypeScript's advanced features like decorators and injections.
Nest.js has excellent documentation and is a great choice for a back-end framework using TypeScript.
Angular is a front-end framework developed by Google and very popular among large enterprise companies that need stable, safe, scalable front ends.
TypeScript is mandatory in an Angular project, and the unique ways Angular and TypeScript interact may take some getting used to if you're new to both tools when you get started. However, the extra safety of TypeScript's code assists Angular in helping developers build complex front-end interfaces.
Other frameworks come with optional TypeScript support that nonetheless makes it easy to bring TS into your project. While you may need to configure TypeScript in these frameworks more than you would in libraries that are TS by default, you can still benefit from its features without much fuss.
Next.js is a React framework that comes with TypeScript support out of the box. You can specify TypeScript with a flag when initializing a new Next project with npx create-next-app@latest --ts
and immediately get started in TS.
Gatsby.js is a well-loved static site generator that pairs nicely with TypeScript. Simply flag it during initialization with
npm init gatsby -ts
and start your TS project with sensible defaults.
Let's show off TypeScript's functionality with a more hands-on example: using TypeScript to write React code.
Popular component-based library React is designed to tackle highly interactive, complex front-end interfaces. With React, modular components of the website are defined using exported JavaScript functions and an HTML-esque custom markup language known as JSX.
These components accept props
(like HTML properties) that pass interactive data through them in the codebase. By defining the props the component expects, you can much more easily control the logical flow of the complicated user interfaces that React is designed to enable.
To use TypeScript in React, begin by naming your file extension .tsx
instead of .jsx
. (Note that while you can use .js and .jsx interchangeably in React, you must also use .tsx when using TypeScript.) Then you can define the shape of the props you pass through each component. Any instance of the component that does not receive the correct props will trigger an error–a huge time-saver!
import React from 'react'; // we need this to make JSX compile
type myCustomProps = {
myString: string,
myNumber: number,
myBoolean: boolean,
myStringArray: string[]
// and so on…
}
export const myCustomComponent = ({
myString,
myNumber,
myBoolean,
myStringArray}: CardProps) => <div>
{myString}
// and so on…
</div>
const myCustomElement = <myCustomComponent myString="my custom string" myNumber={4} />
Although this example is simple, it can easily scale into more complex projects. Imagine an elaborate component, where myCustomProps
is a Card design for a list of products for sale, or a user profile displaying all sorts of dynamic information. If the application knows exactly what it should receive as props into these complex components, countless frustrating bugs can be avoided. This results in a better user experience.
This Fireship video is a great resource on React and TypeScript for further exploration.
Much like the "TS by default" frameworks we listed above, Sanity's Composable Content Cloud will initialize with TypeScript as its language of choice if you start up your studio instance with the CLI.
Under the hood, Sanity uses the well-loved build tool Vite to transpile the TS into JS code.
A studio project generated with default settings will automatically create its own tsconfig.json
file, which you can check out in the docs.
Sanity also uses TSDoc for powerful inline documentation in TypeScript, which remains a work in progress. You can currently use the inline documentation to find the status of different Sanity APIs.
Sanity: leveraging Typescript for better code
Sanity comes with TypeScript definitions, so you'll be able to take advantage of type safety and easier development when designing your own custom studio and content platform. Give it a try today and put your new TS skills to work!