Skip to content
Sanity
Get started
  • Sanity Studio - Flexible editing environment
  • Content Lake - Real-time database
  • Developer experience - Tooling you love
  • Structured content - The philosophy behind Sanity
  • Review changes - View edits & rollback instantly
  • Image pipeline - On-demand transformations
  • E-commerce - Better shopping experiences
  • Marketing sites - Control your story
  • Products & services - Innovate and automate
  • Mobile apps - Content backend for every OS
  • Aether - Unique digital shopping experience
  • Morning Brew - Omnichannel media distribution
  • InVision - Delivering exceptional customer experiences
  • DataStax - Personalization for global audience
  • React
  • Gatsby
  • Next
  • Nuxt
  • Eleventy
  • Netlify
  • Vercel
  • Algolia
  • Documentation
  • Reference
  • Guides
  • Resource library
  • Headless CMS
  • Tools & plugins
  • Project showcase
  • Schemas & snippets
  • Agency partners
  • Technology partners
  • Get support
  • Share your work
  • How I Learned to Expect More From My CMS
EnterprisePricing
Contact salesLog inGet started

Typescript 101

  • TypeScript 101: What is it and why should you use it?
  • TypeScript vs. JavaScript: 7 Key Differences

Categorized in

  • Composable architecture
  1. Resources
  2. Composable architecture
  3. Typescript 101

Last updated October 20th 2022

TypeScript 101: What is it and why should you use it?

  • Joe Holmes

    Software Developer and Technical Writer

You’ve probably heard about TypeScript, a well-loved tool that’s 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 wider world of web development is not immediately clear.

What is TypeScript?

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 special version of JavaScript that comes 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 an increase in 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're certain to 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 some 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.

The purpose of TypeScript

Let's explore what TypeScript can do for developers.

1. Write better code

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.

2. Coding with cruise control

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.

3. Self-writing documentation

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.

How to use TypeScript in your JS project

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.

Examples of projects with TypeScript support

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.

TS by default

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

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

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.

Opt-ins

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

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

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.

React and TypeScript: a great match

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.

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!

Try it out on Sanity
Next
TypeScript vs. JavaScript: 7 Key Differences

Page content

  • What is TypeScript?
  • The purpose of TypeScript
    • 1. Write better code
    • 2. Coding with cruise control
    • 3. Self-writing documentation
  • How to use TypeScript in your JS project
  • Examples of projects with TypeScript support
    • TS by default
    • Opt-ins
  • React and TypeScript: a great match

Platform

Structured ContentDeveloper experienceContent LakeSanity StudioSecurity & Compliance
  • Sanity vs Contentful
  • Sanity vs Strapi
  • Sanity vs Adobe Experience Manager
  • Sanity vs Hygraph
  • Sanity vs Sitecore
  • Sanity vs Storyblok
  • Sanity vs Contentstack
  • Sanity vs Prismic
  • Sanity vs Drupal

Resources

Documentation
  • React Blog
  • Gatsby Blog
  • Next.js Landing Pages
  • Progressive Web Application
  • Single Page Application
  • Svelte & Typescript App
  • Vue & Tailwind Blog
  • Developer Portfolio Templates
  • Form validation with Yup
  • Live Preview with Next.js and Sanity.io
Resource library
  • Agency partners
  • Technology partners
  • Blog Template
  • Personal Website Template
  • Developer Portfolio Templates
  • All Templates
Case Studies
  • Headless CMS
  • What is an API CMS
  • Static Sites 101
  • Headless SEO
  • Localization
  • GraphQL vs REST
  • What is a DXP?
  • Typescript 101
  • React CMS
  • Next.JS CMS
  • CMS for Shopify
  • Content platform
  • Multilingual CMS
  • Static Site CMS
  • Gatsby CMS
  • Node CMS
  • E-commerce CMS
  • Vue CMS
  • Angular CMS
  • GraphQL CMS
  • Newspaper CMS
  • Magazine CMS
  • Mobile apps CMS

Company

Contact SalesEnterpriseCareersTerms of ServiceAccessibility Statement

Stay connected

  • GitHub
  • Slack
  • Twitter
  • YouTube
  • Stack Overflow
  • Blog RSS
  • Newsletter
©Sanity 2023