TypeScript Variables
Introduction
Variables in TypeScript are used to store data that can be referenced and manipulated in a program. TypeScript, being a statically typed language, allows you to define the type of data a variable can hold, providing better type safety and tooling support.
Declaring Variables
In TypeScript, you can declare variables using let
, const
, and var
keywords.
let
The let
keyword declares a block-scoped variable. It is similar to var
, but with better scoping rules.
let count: number = 10;
count = 90; // Valid
const
The const keyword declares a block-scoped variable that cannot be reassigned. It is used for variables that should not change their value.
const name: string = "John";
// name = "Doe"; // Error: Cannot assign to 'name' because it is a constant.
var
The var keyword declares a function-scoped or globally-scoped variable. It is generally recommended to use let or const instead of var due to its scoping issues.
var age: number = 30;
age = 40; // Valid
Variable Types
TypeScript supports various data types for variables, including:
Primitive Types
number
: Represents both integer and floating-point numbers.string
: Represents text data.boolean
: Represents true or false values.null
: Represents a null value.undefined
: Represents an undefined value.symbol
: Represents a unique value.bigint
: Represents large integers.void
: Represents the absence of a value.never
: Represents a value that never occurs.any
: Represents any type.unknown
: Represents an unknown type.
Non-Primitive Types
Array
: Represents a collection of elements of the same type.Tuple
: Represents an array with a fixed number of elements of specific types.Enum
: Represents a set of named constants.Object
: Represents a non-primitive type.Function
: Represents a function type.
Array
An array is a collection of elements of the same type. You can declare an array using square brackets []
or the Array
keyword.
let numbers: number[] = [1, 2, 3, 4, 5];
let strings: Array<string> = ["one", "two", "three"];
Tuple
A tuple is an array with a fixed number of elements of specific types. You can declare a tuple by specifying the types of its elements in order.
let tuple: [string, number];
tuple = ["hello", 10]; // Valid
// tuple = [10, "hello"]; // Error: Type 'number' is not assignable to type 'string'.
Enum
An enum is a way to define a set of named constants. It is useful when you have a fixed set of values that are related.
enum Color {
Red,
Green,
Blue
}
let c: Color = Color.Green;
Any
The any
type allows you to work with any type of value. It is useful when you don't know the type of a variable at compile time.
let randomValue: any = 10;
randomValue = "Hello";
randomValue = true;
Void
The void
type is used when a function does not return a value. It is the absence of a type.
function logMessage(message: string): void {
console.log(message);
}
Never
The never
type represents a value that never occurs. It is used when a function never returns or when it always throws an error.
function throwError(message: string): never {
throw new Error(message);
}
Null and Undefined
In TypeScript, null
and undefined
are subtypes of all other types. You can assign null
or undefined
to a variable of any type.
let u: undefined = undefined;
let n: null = null;
Object
The object
type represents a non-primitive type, i.e., anything that is not number
, string
, boolean
, symbol
, null
, or undefined
.
let obj: object = { name: "John", age: 30 };
Type Assertion
Type assertion is a way to tell the compiler about the type of a variable when you know more about it than the compiler does.
let someValue: any = "this is a string";
let strLength: number = (someValue as string).length;
Type Inference
Type inference is a feature that allows the compiler to determine the type of a variable based on its value.
let message = "Hello, world!"; // Type: string
let count = 10; // Type: number
Type Aliases
Type aliases allow you to create a new name for a type. This can be useful when working with complex types.
type Point = {
x: number;
y: number;
};
let p: Point = { x: 10, y: 20 };
Union Types
Union types allow you to specify that a variable can have more than one type.
let value: string | number;
value = "Hello";
value = 10;
Non-Nullable Types
Non-nullable types allow you to specify that a variable is not null
or undefined
.
let name: string | null = "John";
let age: number | undefined = undefined;
Type Guards with instanceof
Type guards can also be implemented using the instanceof
operator.
class Person {
name: string;
constructor(name: string) {
this.name = name;
}
}
class Animal {
type: string;
constructor(type: string) {
this.type = type;
}
}
function isPerson(value: any): value is Person {
return value instanceof Person;
}
let result: any = new Person("John");
if (isPerson(result)) {
console.log(result.name);
}
Type Guards with in
Type guards can also be implemented using the in
operator.
interface A {
a: number;
}
interface B {
b: string;
}
function isA(value: any): value is A {
return "a" in value;
}
let result: any = { a: 10 };
if (isA(result)) {
console.log(result.a);
}
Conclusion
Understanding variables and their types is fundamental to programming in TypeScript. By leveraging TypeScript's type system, you can write more robust and maintainable code. Use let and const for variable declarations, and choose appropriate types to ensure type safety in your applications.