Data Types in Typescript
Introduction to Data Types in TypeScript
TypeScript, as a statically typed superset of JavaScript, introduces a range of data types that enable developers to use highly-productive development tools and practices. Understanding these data types is crucial for anyone starting out with TypeScript. This tutorial aims to provide a comprehensive overview of these data types, making them easy to understand even for beginners.
Basic Data Types
Boolean
This is the simplest type in TypeScript. It represents a logical entity and can hold two values: true
and false
.
let isDone: boolean = false;
Number
In TypeScript, the number
type represents both integers and floating-point values.
let decimal: number = 6;
let hex: number = 0xf00d;
let binary: number = 0b1010;
let octal: number = 0o744;
String
The string
type is used to represent textual data.
let color: string = "blue";
color = 'red';
Array
TypeScript, like JavaScript, allows you to work with arrays of values. Array types can be written in one of two ways.
let list: number[] = [1, 2, 3];
// or
let list: Array<number> = [1, 2, 3];
Tuple
Tuple types allow you to express an array with a fixed number of elements whose types are known, but need not be the same.
let x: [string, number];
x = ["hello", 10]; // OK
Advanced Data Types
Enum
enum
is a way of giving more friendly names to sets of numeric values.
enum Color {Red, Green, Blue}
let c: Color = Color.Green;
Any
We may need to describe the type of variables that we may not know when we are writing an application. These values may come from dynamic content – from the user, or a 3rd party library. In these cases, we want to opt-out of type checking and let the values pass through compile-time checks. We can use the any
type to achieve this.
let notSure: any = 4;
notSure = "maybe a string instead";
notSure = false; // okay, definitely a boolean
Void
void
is a little like the opposite of any
: the absence of having any type at all. You may commonly see this as the return type of functions that do not return a value.
function warnUser(): void {
alert("This is my warning message");
}
Null and Undefined
In TypeScript, both undefined
and null
have their own types named undefined
and null
respectively. Much like void
, they’re not extremely useful on their own.
let u: undefined = undefined;
let n: null = null;
Conclusion
Understanding the different data types in TypeScript is crucial for writing effective TypeScript code. This article covered all the basic and some advanced data types in TypeScript, providing examples and explanations of how to use them. We hope this has provided a clear and comprehensive overview, making these concepts easy to understand even for beginners. Happy coding!