Do you think IIT Guwahati certified course can help you in your career?
No
Introduction
As a superset of JavaScript, TypeScript offers several advantages over the original language, in addition to all of JavaScript's other outstanding features. It was created and is now maintained by Microsoft as an open-source language. Any environment that supports native JavaScript will also support TypeScript. Applications on the front end and back end can both utilize TypeScript. This blog will learn about the available different TypeScript types, with examples for each.
Data Types
TypeScript determines the type of data allocated to a variable. The colon that comes after the variable name and before the equal sign is used to designate the data types.
Syntax:
const {var name}: {var type} = {var value}
Except for functions and objects, this is the convention used to declare the bulk of TypeScript data types. Certain data types have more complexity.
There are eight data types in JavaScript: a single object data type and seven primitive data types. In JavaScript, everything else is an object. All of them are supported by the TypeScript type system, which offers certain unique types.
Primitive typescript types
A data type without methods and an object status is a primitive data type. Primitive objects cannot be changed. The seven primitive types that TypeScript provides. They are :
string
number
Bigint
boolean
void
Null and undefined
In TypeScript 5, all additional data types are objects.
Special typescript types
With a few exceptions, typescript types are written exactly like JavaScript.
They are:
unknown
void
never
any
The basic descriptions of data types and how to declare them are provided in this blog.
TypeScript Types
The three primary primitives in TypeScript and JavaScript are.
Boolean - values of true or false
number - floating point values and entire numbers
string - textual values
Different kinds of values may be used with the TypeScript language. JavaScript may become a highly typed programming language by using the provided data types. Although JavaScript does not support data types, TypeScript enables us to leverage JavaScript's data type capability. When a programmer uses the type feature in any scripting or object-oriented programming language, TypeScript is essential. Before using the provided values, the type system verifies their accuracy. It ensures that the code behaves as predicted.
By adding an enumeration type to speed things up, TypeScript supports the same kinds that JavaScript would anticipate.
Data types are offered by TypeScript as an optional Type System. The following categories apply to TypeScript types.
Static Types
Static types are defined as "at compile time" or "without running a program" in the context of type systems. Variables, parameters, and objects in a statically typed language have types that the compiler knows at build time. The compiler utilized this data to carry out type-checking.
Static types can be divided into two sub-categories:
Built-in or Primitive Type
User Defined
Built-in or Primitive Type
TypeScript comprises five built-in data types, which are given below.
Number
The number data type in TypeScript is 64-bit floating-point values.
It is used to represent integers and fractions.
Typescript also supports hexadecimal and decimal literals.
It supports the binary and octal literals introduced in ECMAScript 2015.
Syntax
let identifier: number = value;
Example
let decimal: number = 24;
let hex: number = 0xc17n; //number starts with 0x for hexadecimal
let binary: number = 0b1711; //number starts with 0b for binary
let octal: number = 0c305; //number starts with 0c for octal
let big: bigint = 154n;
Both integers and fractions can be represented using the numeric data type. Decimal (Base 10), Hexadecimal (Base 16), Binary (Base 2), and Octal (Base 8) literals are also supported by TypeScript.
Bigint
This will enable the representation of whole numbers greater than 253. Calling the BigInt() method or creating a BigInt literal by appending an "n" to the end of any integer literal, as demonstrated below, will yield a bigint.
Example
let x: bigint = BigInt(240); //BigInt function
let y: bigint = 240n; // BigInt literal
String
Text data is stored using the string data type. Single or double quotes are used to enclose the string value.
Syntax
let identifier: string = " ";
Example 1
let temp=" Cdngnnjs"
let domain=" tech"
The strings are wrapped by the backtick/backquote (') character when they span many lines.
Example 2
let sentence: string =`Hi, tech lovers,
Coding ninjas to your rescue`
Boolean
Boolean data types are straightforward true/false values. The same principles that apply to JavaScript also apply to booleans in TypeScript. Boolean data types are declared using the following syntax:
Syntax
let identifier: BooleanBoolean = Boolean value;
Example
let isDo: boolean = false;
Void
A void represents the absence of any return value.
Syntax
let unusable: void = undefined;
Example
function greetings(): void {
console.log('Hi, cdngnnjs!')
}
This function, after running, returns without returning a value. Hence the return type is void.
Null and Undefined
There are two methods to refer to the null in JavaScript, being null and undefined. Therefore, you may give anything like a number the values null and undefined.
Undefined: In TypeScript and JavaScript, all uninitialized variables are represented by the primitive type Undefined. It only has the value "undefined" as a value. The undefined keyword in TypeScript specifies the type, but it serves no purpose because we can only give it an undefined value.
Example
let a: undefined = undefined;
Null: Represents the absence of object value
Example
let b: null = null;
User-Defined DataType
TypeScript supports the following user-defined data types:
Array
Similar to JavaScript, TypeScript enables you to work with arrays of values. There are two ways to write array types. In the first, an array of that element type is indicated by using the type of the elements followed by [].
Example
let lst: number[ ] = [5, 3, 0];
The second approach uses the Array generic type.
Example
let lst: Array<number> = [5, 0, 3];
Functionally, there is no distinction between how these approaches result in the declaration of an array-type variable. This type can specify arrays containing unidentified or a combination of unidentified and recognized data types.
Any
By giving a variable any type, typescript allows us to forego type verification.
Any is a unique data type that can store any information. This data type is adjustable. This is used when we need clarification on the nature of the data.
Any only applies to typescript. A variable will be viewed as being of any type if its type is not specified and the typescript cannot determine it from the initialization.
Syntax
let identifier: any = value;
Example
let isIt: any = f;
isIt = "is it a string?";
isIt = true;
Tuple
With the aid of a tuple datatype, you may describe an array containing a set number of known data types but not identical entries.
This data type consists of two sets of values of various data types.
It is a specific data type for TypeScript. They are made up of arrays with a fixed number of elements.
This data type is best employed when you know precisely how many variables you need.
Syntax
let name: [string, number];
Example
let x: [string, number];
x = ["hello", 5, "cdngnnjs", 9];
The indices' values can be changed, but not the number of items in the tuple. If we want to change the values of elements, we can do that as long as they match the types we provided when declaring our variable.
Interface
A structure that serves as a contract for our application is called an interface.
It specifies the syntax classes must adhere to, implying that a class that implements an interface must also implement all its members.
Although it cannot be created, the class that implements it may refer to it.
The type-checking interface used by the TypeScript compiler is often called "duck typing" or "structural subtyping."
The interface is unique to TypeScript.
It is solely utilized at build time to do type-checking and find any mistakes that could have escaped our scrutiny. The interface itself is compiled, but the data from it will be used in our final code.
Example
var user = { fName: "Rasha", lName: "AKhader",
namesComp: function () { return "Fname Lname"; }
};
console.log(user.fName);
console.log(user.lName);
console.log(user.namesComp());
Output
Class
Classes serve as a model for building objects and are used to build reusable components.
It is a logical object that houses functions and variables for actions.
Classes in TypeScript are now supported by ES6(ECMAScript 6).
It is distinct from an interface because an implementation is contained within it, whereas an interface does not.
Using classes makes building data much more straightforward than manually typing it out each time we need it.
Classes serve as models for how the data should be defined and what actions it should be able to perform through methods.
Example
class User {
name: string;
}
const user = new User();
user.name = "Rasha";
console.log(user);
Output
Functions
The logical building blocks of a program are called functions.
Programs are clear, maintainable, and reusable using functions.
The name, return type, and parameters of a function are listed in its declaration.
The kind of value we anticipate this function to return must be specified clearly.
You can change the type of a function to void (a data type that denotes the lack of any data) if you wish it to have no return value. Any output from this function will result in a TypeScript error.
Example
function multiply(x: number, y: number): number {
return x * y;
}
Object
The type object represents the non-primitive type.
Similar to how JavaScript objects are defined, TypeScript objects are defined in the same methods.
Even if we declare them in a specific sequence, their order does not matter when we create objects since the property names are immutable.
The never data type represents a value that will never occur.
It is employed as a function's return type even if it does not return a value.
Example
function deBug(): never {
throw new Error("Error found");
}
Built-in types
Here are some common built-in types of Typescript:
Type
Description
number
Represents numeric values, including integers and floating-point numbers.
string
Represents textual data, such as words and sentences.
boolean
Represents true or false values.
object
Represents non-primitive values, i.e., anything not of type number, string, boolean, null, or undefined.
array
Represents a collection of elements of the same type.
tuple
Represents an array with a fixed number of elements, each potentially of different types.
any
Represents any data type, enabling dynamic typing.
void
Represents the absence of a value, often used for functions that don't return anything.
null
Represents the absence of a value.
undefined
Represents a variable that has been declared but not assigned a value.
never
Represents a value that never occurs, commonly used in functions that throw errors or enter infinite loops.
Error in Type Assignment
Type assignment error occurs when you try to assign a value of one type to a variable or parameter that expects another type.
Here's an example of a type assignment error in TypeScript.
let age: number = 20;
let first_name: string = "Ninjas";
// Error: Type 'string' is not assignable to type 'number'.
age = "30";
// Error: Type 'number' is not assignable to type 'string'.
first_name = 30;
Output
The code above has two variables, age and first_name. Both have explicit type annotations (numeric and string respectively).
TypeScript throws a type error when you try to assign a value of the wrong type. This indicates that the assignment is invalid because the types do not match.
Unable to Infer
Unable to Infer refers to situations where the type system cannot automatically determine the data type of a variable or expression. This happens when TypeScript doesn't have enough information to infer the type, or when the type is intentionally left unspecified.
Here are some examples of scenarios where TypeScript can't infer types:
// Type 'any' is inferred implicitly, but it's better to specify explicitly.
let myAge;
In the above code, we declared the variable myAge without providing an explicit type annotation. As a result, TypeScript infers that type as any. This essentially means that the variable can hold any value.
Frequently Asked Questions
What is the purpose of TypeScript?
JavaScript is extended with TypeScript, which also enhances the developer environment.
Is TypeScript a language with OOP?
Contrarily, due to the language structures that TypeScript adds on top of JavaScript closures, it might be seen as an object-oriented language.
Is JavaScript superior to TypeScript?
In terms of reference validation, language features, project scalability, teamwork inside and between teams, developer experience, and code maintainability, TypeScript outperforms JavaScript.
What are function types in TypeScript?
Function types in TypeScript define the type of a function, including its parameters and return value. They ensure strong typing and catch type-related errors during development, enhancing code reliability and maintainability.
Why is any TypeScript type not helpful?
Using any eliminates all of TypeScript's type-checking features.
Conclusion
In this blog, we have discussed TypeScript types in detail, explaining each one in depth by giving an example. If you think this blog has helped you enhance your knowledge of the above question or want to learn more, check out our articles. Visit our website to read more such blogs.
But suppose you have just started your learning process and are looking for questions from tech giants like Amazon, Microsoft, Uber, etc. For placement preparations, you must look at the problems, interview experiences, and interview bundles.