TypeScript is a powerful superset of JavaScript that introduces strong typing and other advanced features, making it easier to build large-scale applications. In this blog post, I’ll dive into the various data types available in TypeScript, providing a foundation for understanding how to work with them.
What is TypeScript?
Before we jump into the data types, let’s do a quick recap of what TypeScript is. TypeScript is a statically typed, compiled superset of JavaScript that allows you to add type annotations to your code. This enables better tooling, improved code quality, and easier collaboration by catching errors at compile time.
While JavaScript is dynamically typed, TypeScript adds the ability to specify types for variables, function parameters, and return values. These types help prevent bugs and improve the developer experience.
Primitive Data Types in TypeScript
TypeScript has several built-in primitive data types, which are the most common types used for variables and constants. Let’s go over each of them:
1. Number
The number
type represents both integer and floating-point numbers. TypeScript does not differentiate between integer and float types, unlike other languages.
let age: number = 25;
let price: number = 19.99;
In TypeScript, the number
type can hold both integer and decimal values, and there is no separate int
or float
type.
2. String
The string
type is used to represent text. You can use single, double, or backticks (template literals) to define string values.
let name: string = "John Doe";
let greeting: string = `Hello, ${name}!`;
String interpolation is also available with backticks, as shown in the example above, allowing you to embed expressions within strings.
3. Boolean
The boolean
type represents a logical value, either true
or false
.
let isActive: boolean = true;
let isCompleted: boolean = false;
Boolean values are frequently used in conditional expressions and control flow.
4. Array
In TypeScript, arrays are strongly typed, meaning you can specify the type of the elements inside the array.
There are two ways to define an array:
- Array type notation:
let numbers: number[] = [1, 2, 3, 4];
- Generic type notation:
let numbers: Array<number> = [1, 2, 3, 4];
Both of these notations are equivalent, but the generic type is often used for more complex types.
5. Tuple
A tuple is an array with a fixed number of elements, where each element can have a different type. It’s useful when you need to store a collection of values with different types.
let person: [string, number] = ["Alice", 30];
In this example, person
is a tuple where the first element is a string
and the second is a number
.
6. Enum
Enums allow you to define a set of named constants. By default, the values of enums are numeric, starting from 0, but you can assign custom values.
enum Direction {
Up = 1,
Down,
Left,
Right
}
let move: Direction = Direction.Up;
In this example, the Direction
enum assigns 1
to Up
, 2
to Down
, and so on. You can also specify custom values if needed.
7. Any
The any
type is a way to opt-out of type checking for a particular variable. This is useful when you don’t know the type of a variable ahead of time or when working with dynamic content (e.g., JSON data).
let data: any = 42;
data = "Now I am a string";
data = [1, 2, 3];
Although any
provides flexibility, it's best to use it sparingly, as it defeats the purpose of type safety in TypeScript.
8. Void
The void
type is used to indicate that a function does not return any value. It’s often used in functions that perform an action but do not return a result.
function logMessage(message: string): void {
console.log(message);
}
In this example, the function logMessage
logs a message but does not return any value.
9. Null and Undefined
In TypeScript, null
and undefined
are distinct types. null
represents the absence of a value, while undefined
represents a variable that has been declared but not initialized.
let notAssigned: undefined = undefined;
let absentValue: null = null;
Both null
and undefined
are also subtypes of any
, so they can be assigned to variables of type any
.
10. Never
The never
type represents a value that never occurs. This is useful for functions that never return, such as those that throw exceptions or enter infinite loops.
function throwError(message: string): never {
throw new Error(message);
}
In this example, the throwError
function never returns any value, which is why its return type is never
.
Type Assertions
Sometimes, TypeScript can’t infer the correct type, or you may know more about the type than TypeScript can deduce. In such cases, you can use type assertions to tell TypeScript the type of a variable.
let someValue: any = "Hello, TypeScript!";
let strLength: number = (someValue as string).length;
Alternatively, you can use the <>
syntax for type assertions (note that this syntax can’t be used in JSX files).
let strLength: number = (<string>someValue).length;
Conclusion
TypeScript introduces a variety of data types that enhance the flexibility, safety, and maintainability of your code. By using these types effectively, you can catch potential errors early in the development process and ensure that your code behaves as expected.
In this post, we covered basic primitive types such as number
, string
and boolean
, as well as more advanced types like tuple
, enum
and any
. Understanding these types is essential to writing clean, bug-free TypeScript code.
Happy coding and don’t forget to explore TypeScript’s powerful features further as you build your projects!
Hope this blog post helps you better understand data types in TypeScript 😍.
Top comments (2)
Also the typescript or even the JSDoc cannot solve the types which are declared in HTML or CSS but the whole ecosystem is a typesafe when these parts also including a type system, not just a JS.
I miss the function, promise related types, different HTML DOM element types, object with a specific keys rules. At that point will be much interesting the typescript ( and JSDoc also )