Note: If you're new to TypeScript, check our Getting Started with TypeScript tutorial first.
TypeScript Data Types
Data types specify the kind of data variables can hold. Some of the main data types in TypeScript are given below:
Data Type | Description | Example |
---|---|---|
number |
Integer or floating-point data. | 3, 3.234, 3e-2, etc. |
string |
Textual data. | 'hello' , "hello world!" , etc. |
boolean |
Any of two values: true or false . |
true , false |
undefined |
A variable that has not been assigned a value. | let firstName: string; |
null |
Represents the intentional absence of any object value. | let firstName = null; |
Array | A list of elements of a single type. | let ages: number[] = [18, 23, 12]; |
Tuple | An array with a fixed size and known data types. | let details: [number, string] = [7, "hello"] |
Object | Key-value pairs of a collection of data. | let student = {name: "John"}; |
any |
Indicates a type of variable that can hold any value. | let anything: any = "Hello"; anything = 5; |
unknown |
Similar to any , but requires more checks. |
let notSure: unknown = 4; |
void |
Used for functions that do not return a value. | function sayHello(): void {...} |
never |
Represents a value that never occurs. | function error(): never {...} |
TypeScript Primitive vs. Non-Primitive Types
TypeScript data types are divided into primitive and non-primitive types.
Types | Description | Examples |
---|---|---|
Primitive | Basic types that can hold a single value. | Strings, numbers, booleans, undefined , null . |
Non-Primitive | Can hold a collection or a more complex structure. | Objects, arrays, tuples, enums, any , void , never , unknown . |
TypeScript Number
In TypeScript, the number
type represents numeric values (integers and floating-point numbers).
- Integers: Numeric values without any decimal parts. Example: 3, -74, etc.
- Floating-Point: Numeric values with decimal parts. Example: 3.15, -1.3, etc.
let integerNumber: number = -3;
console.log(integerNumber);
let floatNumber: number = 3.15;
console.log(floatNumber);
Output
-3 3.15
Special Numeric Values
TypeScript includes unique numeric values that can result from certain arithmetic operations. These special values are Infinity
, -Infinity
, and NaN
(Not-a-Number). For example,
// Division by zero results in Infinity
let number1: number = 3 / 0;
console.log(number1);
// Negative division by zero results in -Infinity
let number2: number = -3 / 0;
console.log(number2);
// Non-numeric operations result in NaN
let number3: number = Number("abc") / 3;
console.log(number3);
Output
Infinity -Infinity NaN
TypeScript String
A string represents textual data. For example, "Programiz"
, "apple"
, etc.
In TypeScript, strings can be enclosed inside single quotes, double quotes, or backticks.
- Single quotes:
'Hello'
- Double quotes:
"Hello"
- Backticks:
`Hello`
We use the string
keyword to declare a variable as a string. For example,
// String enclosed within single quotes
let language: string = 'English';
console.log(language);
// String enclosed within double quotes
let country: string = "USA";
console.log(country);
// String enclosed within backticks
let result: string = `fail`;
console.log(result);
Output
English USA fail
Note: It's important to avoid mismatching quotes within a string (e.g., starting with a single quote and ending with a double quote) as it will lead to syntax errors. For example, the strings 'hello"
and "world'
result in an error.
To learn more about strings, visit TypeScript Strings.
TypeScript Boolean
A boolean data can hold only one of two possible values: true
or false
. We use the boolean
keyword to declare a variable as boolean. For example,
let dataChecked: boolean = true;
console.log(dataChecked); // true
let valueCounted: boolean = false;
console.log(valueCounted); // false
If you want to learn more about booleans, visit TypeScript Booleans.
TypeScript undefined
In TypeScript, the undefined
data type represents a variable that has not been assigned a value. For example,
let item: undefined;
console.log(item);
// Output: undefined
In the above example, we've declared the item variable, but have not assigned any value to it. Hence, it gives undefined
as output when we print the variable.
If you want to learn more about undefined, visit TypeScript undefined.
TypeScript null
In TypeScript, the null
data type represents an intentional absence of any value. For example,
let user: null;
user = null; // The user variable is explicitly set to null
console.log(user);
// Output: null
Here, we assigned null
to the user
variable to indicate that it shouldn't currently hold any data.
Notes:
- Unlike
undefined
, which can imply that a variable has not been initialized,null
is used to indicate a deliberate non-value. - While
undefined
andnull
can be used interchangeably in JavaScript, TypeScript treats them as distinct types (unless configured otherwise).
If you want to learn more about null
, visit TypeScript null.
TypeScript Array
An array stores multiple elements in a single variable and can hold elements of any type. For example,
// Create an array of numbers
let quantities: number[] = [1, 2, 3, 4, 5];
console.log(quantities);
// Output: [1, 2, 3, 4, 5]
Here, we've declared quantities as an array of numbers.
Now, let's create an array that can store strings:
let colors: string[] = ["red", "blue", "green", "yellow"];
console.log(colors);
// Output: [ 'red', 'blue', 'green', 'yellow' ]
Here, colors is an array of strings.
To learn more about arrays, visit TypeScript Arrays.
TypeScript Object
An object is a data type that can store collections of key-value pairs. These pairs can be of other data types like arrays, functions, strings, and numbers. For example,
let person: { name: string; age: number; hobbies: string[] } = {
name: "John",
age: 30,
hobbies: ["reading", "cycling"]
};
console.log(person);
Output
{ name: 'John', age: 30, hobbies: [ 'reading', 'cycling' ] }
In the above example, the person object holds the following key-value pairs:
Key | Value |
---|---|
name |
"John" |
age |
30 |
hobbies |
["reading", "cycling"] |
If you want to learn more about objects, you can visit TypeScript Objects.
TypeScript Tuple
A tuple in TypeScript is a type of array where each element has a specific, predefined type. For example,
// A tuple with a string and a number
let user: [string, number] = ["John", 30];
console.log(user);
// Output: [ 'John', 30 ]
In the above example, we have declared a tuple named user, where
- The first element must be a string.
- The second must be a number.
To learn more about tuples, visit TypeScript Tuples.
TypeScript any
In TypeScript, the any
type allows a variable to hold any type of value without strict type checking. For example,
// Initially, TypeScript interprets the anything variable as a string
let anything: any = "I can be anything!";
console.log(anything);
// Now it's a number
anything = 42;
console.log(anything);
// Now it's a boolean
anything = false;
console.log(anything);
Output
I can be anything! 42 false
In the above example, the variable anything
- starts as a string,
- then changes to a number,
- and finally to a boolean.
The any
type is very flexible but less safe because it bypasses TypeScript's type safety features.
To learn more about any
, visit TypeScript any.
TypeScript unknown
In TypeScript, the unknown
type is similar to any
but is safer, since it requires you to perform some type of checking before performing operations on such values.
let value: unknown = "Hello, TypeScript"; // Value is unknown
// Direct operations on 'unknown' type are not allowed
// console.log(value.toUpperCase()); // Error: Object is of type 'unknown'.
// Correct usage requires type checking
if (typeof value === "string") {
console.log(value.toUpperCase());
}
In the example, we start with a variable value of type unknown
, which means TypeScript doesn't yet know what type of data it holds.
So, before using value, we check if it's a string in order to perform string operations on it. If we don't, we'll get an error.
TypeScript void
In TypeScript, the void
type indicates that a function does not return any value. For example,
function logMessage(): void {
console.log("This function returns nothing.");
}
logMessage();
// Output: This function returns nothing.
In this example, the function logMessage()
is declared with a return type of void
, explicitly stating that it does not return any value.
This is particularly useful for functions where the main purpose is to perform side effects such as displaying a message or writing to a log.
To learn more about void
, visit TypeScript void.
TypeScript never
In TypeScript, the never type represents values that never occur. It is often used to denote functions that never return a value, typically because they throw an exception. For example,
// This function never returns
function throwError(message: string): never {
throw new Error(message);
}
try {
// Call the function
throwError("Something went wrong!");
}
catch (error) {
// Print the error message
console.log((error as Error).message);
}
// Output: Something went wrong!
Here, in the throwError()
function, never
indicates that the function will always throw an error and never complete normally.
Types Present in TypeScript But Absent in JavaScript
The following types are not native to JavaScript but have been added by TypeScript:
tuple
never
unknown
void