DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Because the DevOps movement has redefined engineering responsibilities, SREs now have to become stewards of observability strategy.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Related

  • TypeScript: Useful Features
  • Immutability in JavaScript — When and Why Should You Use It
  • Efficiently Migrating From Jest to Vitest in a Next.js Project
  • An Introduction to Object Mutation in JavaScript

Trending

  • Navigating and Modernizing Legacy Codebases: A Developer's Guide to AI-Assisted Code Understanding
  • The Role of AI in Identity and Access Management for Organizations
  • Navigating Change Management: A Guide for Engineers
  • Analyzing Techniques to Provision Access via IDAM Models During Emergency and Disaster Response
  1. DZone
  2. Coding
  3. Languages
  4. Ultimate Guide to Types in TypeScript

Ultimate Guide to Types in TypeScript

Typescript is a strongly typed language. In this guide we'll be showing you everything you need to know about how to use types in Typescript

By 
Johnny Simpson user avatar
Johnny Simpson
DZone Core CORE ·
Mar. 20, 22 · Tutorial
Likes (8)
Comment
Save
Tweet
Share
8.1K Views

Join the DZone community and get the full member experience.

Join For Free

TypeScript is a strongly typed language built on top of Javascript. As such, types have to be defined in TypeScript when we write our code, rather than inferred as they normally are in Javascript.

In this guide, we'll be diving into how types work in TypeScript, and how you can make the most of them. If you're totally new to TypeScript, start with our guide on making your first TypeScript project.

The Fundamental Types in TypeScript

Javascript has a number of different types. If you want to learn about how types work in Javascript, read our guide here. In this guide, we'll be covering the main types you can use in TypeScript. An understanding of Javascript types will be useful, but for simplicity, below is a list the most fundamental TypeScript types you will see the most:

  • undefined - when something is not defined in the code, or does not exist.
  • any - refers to any type - essentially not enforcing a type at all.
  • enum - an enum - see here for more on enums.
  • number - a number between -2^53 - 1 and 2^53 - 1, i.e. 1.
  • string - a combination of characters i.e. test.
  • boolean - true or false.
  • bigint - a number bigger than 253 - 1.
  • symbol - a completely unique identifier.
  • function - self-explanatory - a function.
  • object - an object or array
  • never - used in functions - for when a function never returns a value, and only throws an error.
  • void - used in functions - for when a function never returns a value.

Custom Types in TypeScript

TypeScript also allows us to define our own custom types. You can learn about that here.

Fundamentals of Types in TypeScript

Now that we've outlined all the fundamental types that TypeScript uses, let's take a look at how they work. First, let's start with syntax basics.

Using TypeScript Types in Variables

The syntax of types on variables in TypeScript is relatively straight forward. If we expect a variable to be of a specific type, we define it after a colon, after the variable name. For example, the below variable is defined as having type number.

TypeScript
 
let x:number = 5;


Similarly, a string type might look like this:

TypeScript
 
let x:string = "Some String";


If you do not define the type of a variable properly, TypeScript will throw an error. For example, let x:string = 5 would throw the following error:

Type 'number' is not assignable to type 'string'.


Defining Object Types in TypeScript

Objects are everywhere in Javascript, and it's no different in TypeScript. An object in TypeScript is of type object, but values inside an object also have their own types. In the most basic example, we can define a variable as type object, which refers to an object of any length or value set:

TypeScript
 
let myObject:object = { a: 1 };


If we want to get a little more complicated, we can also define the expected types of properties within an object. Suppose we have an object where we have 3 properties:

  • name, of type string
  • age, of type number
  • interests, of type object, where interests is optional We can define each of these explicitly, using the following format:
TypeScript
 
let userOne:{ name: string, age: number, interests?: object } = { name: "John Doe", age: 24, interests: [ 'skiing', 'hiking', 'surfboarding' ] };


As you might notice, this is becoming a little messy! Often, when we do this, we'll create custom types. As an example, here is the same code using a custom type instead:

TypeScript
 
type User = {
  name: string,
  age: number,
  interests?: object
}

let userOne:User = { name: "John Doe", age: 24, interests: [ 'skiing', 'hiking', 'surfboarding' ] };


Now we have a nice clean User type that we can apply to any variable or function. Next, let's look at arrays.

Defining Array Types in TypeScript

Since Arrays and Objects can contain their own types within, how we define them is slightly different. For arrays, the most basic way to define the type is to use the type[] syntax. For example, an array of strings looks like this:

TypeScript
 
let arrayOfStrings:string[] = [ 'some', 'strings' ];


Here, string can be replaced with any other valid type. If we know the exact number and types of elements that will appear in our array, we can define it like this:

TypeScript
 
let myArray:[ string, number ] = [ "some", 15 ]


In TypeScript, when we define an array like this, with fixed types and a fixed length, it is known as a Tuple.

Mixed Array Types in TypeScript

Sometimes, an array may be made of multiple types, but have an unknown length. In this situation, we can use a union type. For instance, an array of unknown length which only consists of strings and numbers, looks could be defined as this:

TypeScript
 
let myArray:(string|number)[] = [ "some", 15 ]


Again, for more complicated types, though, we may want to define our own types.

Using TypeScript Types in Functions

The same principles ultimately apply to functions - the only difference here being that a function also often has a return value. Let's start by looking at a simple example without a return function. Notice that we define the type of each argument in the function:

TypeScript
 
function generateName(firstName: string, lastName: string) {
  console.log(`Hello ${firstName} ${lastName}`)
}

// Run the function
generateName("John", "Doe");


This function will run successfully, since we've given the right types when we ran the function (i.e. both arguments are strings).

One fundamental difference between TypeScript and Javascript, is that if we were to run generateName("John");, TypeScript would give us the following error:

Expected 2 arguments, but got 1.


Since TypeScript is far more strict than Javascript, it was expecting two arguments - not one. If we want this to work, we have to explicitly tell TypeScript that argument two is optional. We can do this by adding a ? after the second argument. As such, the following code works fine, with no errors:

TypeScript
 
function generateName(firstName: string, lastName?: string) {
  console.log(`Hello ${firstName} ${lastName}`)
}
// Run the function
generateName("John");


Using TypeScript in Functions with Return Types

Adding a return type in TypeScript is straightforward. If a function returns something using the keyword return, we can enforce what type the data from return should be. Since we are returning nothing - so our return type is known as void.

If we want to add our return type to this function, we use the same :, so our code looks like this:

TypeScript
 
// Note that we have added : void!
function generateName(firstName: string, lastName: string): void {
  console.log(`Hello ${firstName} ${lastName}`)
}
// Run the function
generateName("John", "Doe");


Now TypeScript knows that this function will only ever return nothing. If it starts to return something, TypeScript will throw an error:

Type 'string' is not assignable to type 'void'.


As such, TypeScript helps protect us from unknown pieces of code trying to return data in functions. Let's suppose we want to change our function to return, rather than console.log. Since our return will be of type string, we simply change our function's return type to string:

TypeScript
 
function generateName(firstName: string, lastName: string): string {
  return `Hello ${firstName} ${lastName}`;
}
// Run the function
let firstUser = generateName("John", "Doe");


Writing Functions as Variables in TypeScript

Javascript has a common notation where functions are written as variables. In TypeScript, we can do the same, we just have to define the types up front. If we wanted to convert our function above to the variable format, it would look like this:

TypeScript
 
let generateName:(firstName: string, lastName: string) => string = function(firstName, lastName) {
  return `Hello ${firstName} ${lastName}`;
}


Notice one small difference here, is that the return type is after =>, rather than :. Also note, that we did not define types for firstName or lastName in the function() itself - this is because we defined them as part of the variable - so no need to do so again.

Conclusion

After this, you should have a good understanding of how types work in TypeScript. In this article, we have covered:

  • The fundamental and most common TypeScript types
  • How to define variable and function types in TypeScript
  • How to set the return type of a function in TypeScript
  • Creating basic custom types for objects in TypeScript
  • How to create array and tuple types in TypeScript

I hope you've enjoyed this introduction to TypeScript types. You can find more TypeScript content here.

TypeScript Object (computer science) JavaScript Data structure

Published at DZone with permission of Johnny Simpson, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • TypeScript: Useful Features
  • Immutability in JavaScript — When and Why Should You Use It
  • Efficiently Migrating From Jest to Vitest in a Next.js Project
  • An Introduction to Object Mutation in JavaScript

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!