Understanding DataTypes in TypesScript (2024)

TypeScript is referred to as optional static type language which means you can ask the compiler to ignore the type of a variable if you want to take the advantage of the dynamic type. This mixing of static and dynamic typing is also available in C# where you can define the static typed using primary datatype and secondary datatype and also you can define the dynamic type using the dynamic keyword.

Just like JavaScript and any such programming or the scripting language, the TypeScript language also provides the set of basic data types to work with different types of data such as numbers, strings, etc. there are some of the data types which are being supported with TypeScript are number, string, enum, boolean, undefined, void, null, any, never, Array and tuple so will discuss most of them in this article.

Here, we will discuss the TypeScript Types which you can use to write your TypeScript code.

Any Type

The Any type is a supertype of all types which represents any JavaScript value. You can assign any type of value to it. The any keyword is used to define Any type in TypeScript.

The Any type is useful when we do not know the type of value (which might come from an API or a 3rd party library) and we want to skip the type-checking on compile time so there won't be any error visible for the data type as it considers all the values same.

any.ts

function ProcessData(x: any, y: any) { return x + y;}let result: any;result = ProcessData("Hello ", "Any!"); //Hello Any!result = ProcessData(2, 3); //5

The compiled JavaScript (ES5) code for the above TypeScript code is given below:

any.js function ProcessData(x, y) { return x + y;}var result;result = ProcessData("Hello ", "Any!"); //Hello Any!result = ProcessData(2, 3);

Primitive Types

The primitive types in TypeScript are the Number, Boolean, String, Void, Null, Undefined types, and Enum types.

Number

The Number primitive type is equivalent to JavaScript primitive type number, which represents double precision 64-bit floating-point values. The number keyword is used to define Number type in TypeScript. TypeScript supports decimal, hexadecimal, binary and octal literals, and in addition to the hexadecimal and decimal values, the TypeScript also supports binary and octal types which were introduced back in ECMAScript 2015.

number.ts

let nondecimal: number = 2;let decimal: number = 2.4;let hexadecimal: number = 0xf;let binary: number = 0b100;let octal: number = 0o7;

The compiled JavaScript (ES5) code for the above TypeScript code is given below:

number.js

var nondecimal = 2;var decimal = 2.4;var hexadecimal = 0xf;var binary = 4;var octal = 7;

Boolean

The Boolean primitive type is equivalent to JavaScript primitive type boolean which accepts a value that is either true or false. The boolean keyword is used to define a Boolean type in TypeScript.

boolen.ts

let yes: boolean = true;let no: boolean = false;

The compiled JavaScript (ES5) code for the above TypeScript code is given below:

boolen.js

var yes = true;var no = false;

String

The String primitive type is equivalent to JavaScript primitive type string and represents the sequence of characters stored as Unicode UTF-16 code units. The string keyword is used to define String type in TypeScript.

Just like JavaScript, TypeScript also uses double quotes (") or single quotes (') to surround string data.

string.ts

let name: string = "Shailendra Chauhan";let site: string = 'www.gurukulsight.com';

The compiled JavaScript (ES5) code for the above TypeScript code is given below:

string.js

var name = "Shailendra Chauhan";var site = 'www.gurukulsight.com';

Void

The Void primitive type represents the absence of a value. The void keyword is used to define a Void type in TypeScript but it is not useful because you can only assign null or undefined values to it.

The void type is mostly used as a function return type that does not return a value or as a type argument for a generic class or function.

void.ts

function displayMeassge(): void { console.log("Welcome to Gurukulsight!");}let unusable: void = undefined;

The compiled JavaScript (ES5) code for the above TypeScript code is given below:

void.js

function displayMeassge() { console.log("Welcome to Gurukulsight!");}var unusable = undefined;

Null

The Null primitive type is equivalent to JavaScript primitive type null which accepts the one and only value null. The null keyword is used to define Null type in TypeScript but it is not useful because you can only assign a null value to it.

The Null type is a subtype of all types except the undefined type. Hence, you can assign null as a value to all primitive types, object types, union types, and type parameters.

null.ts

let num: number = null;let bool: boolean = null; let str: string = null;let n: null = null; //not useful, since you can assign only null value

The compiled JavaScript (ES5) code for the above TypeScript code is given below:

null.js

var num = null;var bool = null;var str = null;var n = null;

Undefined

The Undefined primitive type is equivalent to JavaScript primitive type undefined and all uninitialized variables in TypeScript and JavaScript have one and only value that is undefined. The undefined keyword is used to define Undefined type in TypeScript but it is not useful because you can only assign undefined value to it.

The Undefined type is also a subtype of all types. Hence, you can assign undefined as a value to all primitive types, object types, union types, and type parameters.

undefined.ts

let num: number = undefined;let bool: boolean = undefined;let str: string = undefined;let un: undefined = undefined; //not useful, since you can assign only undefined value

The compiled JavaScript (ES5) code for the above TypeScript code is given below:

undefined.js

var num = undefined;var bool = undefined;var str = undefined;var n = undefined;

Symbols

A symbol is a new, primitive data type introduced in ES6 just like number and string. A symbol value is created by calling the Symbol constructor.

symbols1.ts

let s1 = Symbol();let s2 = Symbol("mySymbol");

Symbols are immutable and unique. When you create two symbols with the same description then they will be unique and immutable. Just like strings, symbols can be used as keys for object properties.

symbols2.js

let s1 = Symbol("mySymbol Description");let s2 = Symbol("mySymbol Description");s1 === s2; // false, symbols are unique

Here is the list of some built-in symbols:

  1. Symbol.hasInstance

    - Used for determining whether an object is one of the constructor’s instances.
  2. Symbol.match

    - Used for matching the regular expression against a string.
  3. Symbol.iterator

    - Returns the default iterator for an object and is called by the for-of loop.
  4. Symbol.search

    - Returns the index number within a string that matches the regular expression.
  5. Symbol.split

    - Splits a string at the indices that match the regular expression.

Enum

An enum is a way to give friendly names to a set of numeric values. The enum keyword is used to define Enum type in TypeScript. By default, the value of the enum’s members starts from 0. But you can change this by setting the value of one of its members.

In TypeScript, there are two types of enums that are supported which are string and number enum where the number enum can be auto incremented whereas the string enum does not support auto incremented values.

enum.ts

enum Courses {TypeScript, Ionic, Angular2, NodeJS};let tscourse: Courses = Courses.TypeScript;console.log(tscourse); //0

The compiled JavaScript (ES5) code for the above TypeScript code is given below:

enum.js

var Courses;(function (Courses) { Courses[Courses["TypeScript"] = 0] = "TypeScript"; Courses[Courses["Ionic"] = 1] = "Ionic"; Courses[Courses["Angular2"] = 2] = "Angular2"; Courses[Courses["NodeJS"] = 3] = "NodeJS";})(Courses || (Courses = {}));;var tscourse = Courses.TypeScript;console.log(tscourse); //0

In the previous example, we can start the enum’s members value from 2 instead of 0.

enum.ts

enum Courses {TypeScript=2, Ionic, Angular2, NodeJS};let tscourse: Courses = Courses.TypeScript;console.log(tscourse); //2

The compiled JavaScript (ES5) code for the above TypeScript code is given below:

enum.js

var Courses;(function (Courses) { Courses[Courses["TypeScript"] = 2] = "TypeScript"; Courses[Courses["Ionic"] = 3] = "Ionic"; Courses[Courses["Angular2"] = 4] = "Angular2"; Courses[Courses["NodeJS"] = 5] = "NodeJS";})(Courses || (Courses = {}));;var tscourse = Courses.TypeScript;console.log(tscourse); //2

An enum type can be assigned to the Number primitive type, and vice versa.

enum.ts

enum Courses { TypeScript = 2, Ionic, Angular2, NodeJS };let tscourse: Courses = Courses.Ionic;let c: number = tscourse; //3

The compiled JavaScript (ES5) code for the above TypeScript code is given below:

enum.js

var Courses;(function (Courses) { Courses[Courses["TypeScript"] = 2] = "TypeScript"; Courses[Courses["Ionic"] = 3] = "Ionic"; Courses[Courses["Angular2"] = 4] = "Angular2"; Courses[Courses["NodeJS"] = 5] = "NodeJS";})(Courses || (Courses = {}));;var tscourse = Courses.Ionic;var c = tscourse;
What do you think?

In TypeScript, using the various types we define the data type of variables based on the variable being assigned to it. If we do not assign the data type, then typescript treats it as any type which can assume the data type is not mentioned. The any data type is the base type of all other types available in TypeScript. The primitive data types available such as number, string, bigint, boolean, null, and undefined, and all other types are derived from the objects.

I hope you will enjoy the Data Type in TypeScript while developing your web app. I would like to have feedback from my blog readers. Your valuable feedback, question, or comments about this article are always welcome.

Take our Typescript skill challenge to evaluate yourself!

Understanding DataTypes in TypesScript (1)

In less than 5 minutes, with our skill challenge, you can identify your knowledge gaps and strengths in a given skill.

GET FREE CHALLENGE

Understanding DataTypes in TypesScript (2024)

FAQs

How to define data types in TypeScript? ›

Array. The array data type is a collection of the same elements. It stores the elements, which you can access or update using the array index that starts from 0. The array of any data type can be defined as data_type[] or Array<data_type>, where <data_type> can be any primitive or non-primitive data type.

Do I need to type everything in TypeScript? ›

You don't have to type everything explicitly in typescript. Actually, I would argue in most cases you should let typescript do it for you via type inference. That's the best way to do it. Makes the code more readable while preserving the benefits of using it.

How to check if data is of type in TypeScript? ›

In Typescript, we have three ways to work with it using:
  1. typeof: the keyword helps to check values types, like boolean, string, number, etc.
  2. instanceof: the keyword to compare the object instance with a class constructor.
  3. type guards: The powerful way to check types using typescript feature language.
Aug 10, 2022

What is the basic understanding of TypeScript? ›

TypeScript is a syntactic superset of JavaScript which adds static typing. This basically means that TypeScript adds syntax on top of JavaScript, allowing developers to add types. TypeScript being a "Syntactic Superset" means that it shares the same base syntax as JavaScript, but adds something to it.

How do you explain data types? ›

A data type is an attribute associated with a piece of data that tells a computer system how to interpret its value. Understanding data types ensures that data is collected in the preferred format and the value of each property is as expected.

What are the three main simple types in TypeScript? ›

TypeScript Simple Types
  • boolean - true or false values.
  • number - whole numbers and floating point values.
  • string - text values like "TypeScript Rocks"

How to get the type of data in TypeScript? ›

The typeof operator is a straightforward JavaScript feature that TypeScript also utilizes. It returns a string indicating the data type of its operand. Example: In this example, we are using typeof Operator to get the type of a variable.

How to check if type is string in TypeScript? ›

Using typeof Operator

The typeof operator is the most straightforward method to check if a variable is a string. It returns a string indicating the type of the unevaluated operand. Pros: Simple and fast; works well for most use cases. Cons: Cannot differentiate between string primitives and String objects.

How to check if type is a number in TypeScript? ›

Use typeof to check if a value is classified as a number primitive. To safeguard against NaN , check if val === val (as NaN has a typeof equal to number and is the only value not equal to itself).

What to avoid in TypeScript? ›

10 Common Mistakes in Typescript Development
  • Overuse of type “any”
  • Misusing “as” Casts.
  • Ignoring Type-check Errors and Warning.
  • Not Using Strict Mode.
  • Implicit “any” in Function Return Types.
  • Not using “const” and “read-only” correctly.
  • Inconsistent Coding Conventions.
  • Overcomplicating Types.

Is it hard to learn TypeScript? ›

TypeScript is not harder to learn than Javascript, no. Ultimately TypeScript is like an amped up version of JavaScript. If you're already familiar with JavaScript, picking up TypeScript won't be too hard. TypeScript introduces some extra concepts like static typing, but overall, it's similar to JavaScript.

What should I learn before learning TypeScript? ›

The answer is that you can't learn TypeScript without learning JavaScript! TypeScript shares syntax and runtime behavior with JavaScript, so anything you learn about JavaScript is helping you learn TypeScript at the same time.

How do you specify a type in TypeScript? ›

TypeScript - Type Annotations

We can specify the type using :Type after the name of the variable, parameter or property. There can be a space after the colon. TypeScript includes all the primitive types of JavaScript- number, string and boolean. In the above example, each variable is declared with their data type.

How do you declare data in TypeScript? ›

In TypeScript, you can declare a variable using the `let` or `const` keyword, just like in JavaScript. However, TypeScript also allows you to specify the variable type using type annotations. let myObject: { name: string, age: number } = { name: "Alice", age: 30 };

How do you give types in TypeScript? ›

Creating Types from Types
  1. Generics - Types which take parameters.
  2. Keyof Type Operator - Using the keyof operator to create new types.
  3. Typeof Type Operator - Using the typeof operator to create new types.
  4. Indexed Access Types - Using Type['a'] syntax to access a subset of a type.

How do you define multiple types in TypeScript? ›

TypeScript lets you create a union type that is a composite of selected types separated by a vertical bar, | .
  1. let myBoolean: string | boolean;
  2. myBoolean = 'TRUE'; // string type.
  3. myBoolean = false; // boolean type.

Top Articles
How Long Do Solar Panels Last? (2024 Guide)
7 key benefits of ESG investing | Finance Alliance
Www.mytotalrewards/Rtx
Odawa Hypixel
Research Tome Neltharus
Lifebridge Healthstream
Steamy Afternoon With Handsome Fernando
41 annonces BMW Z3 occasion - ParuVendu.fr
Encore Atlanta Cheer Competition
Uc Santa Cruz Events
Find your energy supplier
Herbalism Guide Tbc
Char-Em Isd
Billionaire Ken Griffin Doesn’t Like His Portrayal In GameStop Movie ‘Dumb Money,’ So He’s Throwing A Tantrum: Report
Honda cb750 cbx z1 Kawasaki kz900 h2 kz 900 Harley Davidson BMW Indian - wanted - by dealer - sale - craigslist
Zalog Forum
50 Shades Of Grey Movie 123Movies
2013 Ford Fusion Serpentine Belt Diagram
Www.dunkinbaskinrunsonyou.con
Gotcha Rva 2022
Deshuesadero El Pulpo
Cars & Trucks - By Owner near Kissimmee, FL - craigslist
Craigslist Rentals Coquille Oregon
Free T33N Leaks
Usa Massage Reviews
Movies - EPIC Theatres
Emuaid Max First Aid Ointment 2 Ounce Fake Review Analysis
lol Did he score on me ?
Airg Com Chat
UPC Code Lookup: Free UPC Code Lookup With Major Retailers
Clearvue Eye Care Nyc
Petsmart Distribution Center Jobs
Indiana Immediate Care.webpay.md
The Legacy 3: The Tree of Might – Walkthrough
Helloid Worthington Login
How are you feeling? Vocabulary & expressions to answer this common question!
Albertville Memorial Funeral Home Obituaries
Stanley Steemer Johnson City Tn
Craigslist Florida Trucks
Gravel Racing
Casamba Mobile Login
Windshield Repair & Auto Glass Replacement in Texas| Safelite
Rage Of Harrogath Bugged
Grizzly Expiration Date Chart 2023
Truck Works Dothan Alabama
Iman Fashion Clearance
Unblocked Games 6X Snow Rider
Das schönste Comeback des Jahres: Warum die Vengaboys nie wieder gehen dürfen
Pas Bcbs Prefix
Lesson 5 Homework 4.5 Answer Key
German American Bank Owenton Ky
How to Find Mugshots: 11 Steps (with Pictures) - wikiHow
Latest Posts
Article information

Author: Mr. See Jast

Last Updated:

Views: 6764

Rating: 4.4 / 5 (75 voted)

Reviews: 82% of readers found this page helpful

Author information

Name: Mr. See Jast

Birthday: 1999-07-30

Address: 8409 Megan Mountain, New Mathew, MT 44997-8193

Phone: +5023589614038

Job: Chief Executive

Hobby: Leather crafting, Flag Football, Candle making, Flying, Poi, Gunsmithing, Swimming

Introduction: My name is Mr. See Jast, I am a open, jolly, gorgeous, courageous, inexpensive, friendly, homely person who loves writing and wants to share my knowledge and understanding with you.