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

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Mule 4 DataWeave(1.x) Script To Resolve Wildcard Dynamically
  • How to Use State Inside of an Effect Component With ngrx
  • Data Governance Essentials: Glossaries, Catalogs, and Lineage (Part 5)
  • How to Simplify Complex Conditions With Python's Match Statement

Trending

  • Rethinking Recruitment: A Journey Through Hiring Practices
  • AI’s Role in Everyday Development
  • Performance Optimization Techniques for Snowflake on AWS
  • Concourse CI/CD Pipeline: Webhook Triggers
  1. DZone
  2. Data Engineering
  3. Data
  4. What Are the Basic Data Types in TypeScript?

What Are the Basic Data Types in TypeScript?

A developer goes over the several different data types available in TypeScript, and gives some example code for each data type.

By 
Kunal Chowdhury user avatar
Kunal Chowdhury
·
Updated Jul. 09, 18 · Tutorial
Likes (5)
Comment
Save
Tweet
Share
189.2K Views

Join the DZone community and get the full member experience.

Join For Free

Like JavaScript and any other language, TypeScript also provides basic data types to handle numbers, strings, etc. Some common data types in TypeScript are: number, string, boolean, enum, void, null, undefined, any, never, Array and tuple.

Let's learn more about these basic data types of TypeScript, which you will always need to use. Let's learn with suitable examples.

Number Types

In TypeScript, numbers are floating point values that have a type of number. You can assign any numeric values including decimals, hexadecimals, binary, and octal literals. But to use binary and octal literals, you must use a TypeScript version which follows ECMAScript 2015 or higher.

Here are some examples of declaring numeric values:

let decimalValue: number = 10;
let hexaDecimalValue: number = 0xf10b;
let binaryValue: number = 0b110100;
let octalValue: number = 0o410;

String Types

When you want to use textual data, string types are used and get denoted by the keyword string. Like JavaScript, TypeScript also uses double quotes (") and single quotes (') to surround the string value.

let firstName: string = "Kunal"; // using double quotes
let lastName: string = 'Chowdhury'; // using single quotes

When you want to span a string to multiple lines and/or have to embed expressions (${expression}), you can use templated strings. The templated strings are surrounded by a backquote/backtick (`) as shown in the below code snippets:

let firstName: string = "Kunal";
let lastName: string = "Chowdhury";

let message: string = `Hi, my name is: ${firstName} ${lastName}`;
let spannedMessage: string = `Hi,
My name is: ${firstName} ${lastName}`;

Boolean Types

To use boolean data types in TypeScript, for declaring variables, use the boolean keyword. Here's a simple code to declare a boolean type variable:

let isPrimaryAccount: boolean = true;
let hasCards: boolean = false;

Enum Types

Enumerated data types (enums) are a set of numeric values with more friendly names. It's an addition on top of JavaScript that TypeScript offers. The variables of enumerated data types are declared with the keyword enum. Here's how you can declare an enum variable and use it in TypeScript:

enum CardTypes { Debit, Credit, Virtual }
let card: CardTypes = CardTypes.Debit;

By default, the enum values start from 0 (zero), but you can also set it by manually entering the value of its members. Consider the following two examples:

enum CardTypes { Debit = 1, Credit, Virtual }
enum CardTypes { Debit = 1, Credit = 3, Virtual = 5 }

Void Types

In general, this type of data types are used in functions that do not return any value. For example, function showMessage(): void { ... }. In TypeScript, you can also declare a variable of type void, but can only assign undefined or null to them. We will discuss undefined and null types in the following sections.

You may like to read: TypeScript Tutorial for Beginners

Null Types

You can declare a variable of type null using the null keyword and can assign only null value to it. As null is a subtype of all other types, you can assign it to a number or a boolean value.

let nullValue: null = null;
let numericValue: number = null;

Undefined Types

You can use the undefined keyword as a data type to store the value undefined to it. As undefined is a subtype of all other types, just like null, you can assign it to a number or a boolean value. 

let undefinedValue: undefined = undefined;
let numericValue: number = undefined;

Any Types

While writing code for which you are unsure of the data type of a value, due to its dynamic content, you can use the keyword any to declare said variable. This is often useful when you are seeking input from users or at third-party library/service. This is also useful when you are declaring an array which has a mixed data type. It's just like the dynamic keyword available in C#. For example:

let dynamicValue: any = "Kunal Chowdhury";
dynamicValue = 100;
dynamicValue = 0b1100101;
dynamicValue = true;

let dynamicList: any[] = [ "Kunal Chowdhury",
                           "Free User",
                           21,
                           true
                         ];

Never Types

The never type represents the data type of values that never occur. For example, the following function that always throws an exception can never return a value. Thus, the return type of the function can be set as never. Here's the function declaration:

function throwError(message: string): never {
    throw new Error(message);
}

Array Types

Just like JavaScript, you can work with arrays in TypeScript and can define them in either of the following two ways; the second approach, however, is the more generic way to declare arrays:

let marks: number[] = [80, 85, 75];
let marks: Array<number> = [80, 85, 75];

Tuple Types

A tuple is a data type that allows you to create an array where the type of a fixed number of elements are known but need not be same. While accessing an element of a Tuple with a valid known index, the data of correct type will be returned. In case you access an element outside the set of known indices, a union type will be used. Consider the following code snippet as an example:

// correct
let person: [string, number] = ["Kunal", 2018];

// error
let person: [string, number] = [2018, "Kunal"];

// correct
let person: [string, number] = ["Kunal", 2018, "India"];

// correct
let person: [string, number] = ["Kunal", 2018, 21];

// error
let person: [string, number] = ["Kunal", 2018, true];
Data (computing) TypeScript Data Types

Published at DZone with permission of Kunal Chowdhury, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Mule 4 DataWeave(1.x) Script To Resolve Wildcard Dynamically
  • How to Use State Inside of an Effect Component With ngrx
  • Data Governance Essentials: Glossaries, Catalogs, and Lineage (Part 5)
  • How to Simplify Complex Conditions With Python's Match Statement

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!