This is the second note in the TypeScript series. In this post, we will explore the fundamentals of TypeScript.
The Fundamentals
As you know, JavaScript has built-in types such as string
, number
, bigint
, boolean
, undefined
, null
, and object
. TypeScript extends these types and introduces new ones, including any
, array
, unknown
, enum
, and tuple
.
any
The any
type is a special type that you can use when you don’t want a particular value to cause type-checking errors.
When a value is of type any
, you can:
- Access any of its properties (which will also be of type
any
). - Call it like a function.
- Assign it to or from a value of any type.
- Perform virtually anything else that is syntactically valid in TypeScript.
Example:
function greetings(name: any) {
console.log(`Hello, ${name}!`);
}
greetings("Bino"); // Outputs: Hello, Bino!
greetings(33); // Outputs: Hello, 33!
let user; // This variable will also be treated as `any` since it has no assigned value.
However, keep in mind that if you declare a variable as any
, the TypeScript compiler will ignore type errors associated with that variable. This can lead to potential runtime issues, so it’s best to use any
sparingly.
Array
To specify the type of an array, such as [1, 2, 3, 4]
, you can use the syntax number[]
. This syntax works for any type (e.g., string[]
for an array of strings).
Alternatively, you can use the generic Array<elemType>
syntax, as shown below. Both syntaxes produce the same result:
let numbers: number[] = [1, 2, 3, 4];
let list: Array<number> = [1, 2, 3, 4];
Both approaches are interchangeable, so you can choose whichever suits your style or project standards.
Tuple
A tuple type is another sort of Array
type that knows exactly how many elements it contains, and exactly which types it contains at specific positions.
As shown below, when accessing an element with a known index, the correct type is retrieved. Also accessing outside the array size will throw an error. For more detail read here.
let user: [string, number] = ["Bino", 33];
console.log(user[0]);
// OK
console.log(user[0].substring(1));
// Property 'substring' does not exist on type 'number'.
console.log(user[1].substring(1));
For more read here.
Enums
Enums allow a developer to define a set of named constants. Using enums can make it easier to document intent, or create a set of distinct cases. TypeScript provides both numeric and string-based enums.
Numeric enums
An enum can be defined using the enum
keyword. As you can see the below up
is initialized with 1
. All of the following numbers are auto-incremented from that point on. In other words, Direction.up
has the value 1
, down has 2
, left has 3
, and right has 4
.
If you are not initializing with any value, the value will start with 0
enum direction {
up = 1,
down,
left,
right
};
String enums
In a string enum, each member has to be constant-initialized with a string literal, or with another string enum member.
enum direction {
up = "UP",
down = "DOWN",
left = "LEFT",
right = "RIGHT"
};
For more read here.
Functions
In TypeScript, you can use type annotations to specify the types of parameters a function accepts. Add these annotations after each parameter in the function declaration.
// Parameter type annotation
function greet(name: string) {
console.log("Hello, " + name.toUpperCase() + "!!");
}
greet(2); // This would cause a runtime error if executed!
Additionally, you can specify the function’s return type by adding a return type annotation after the parameter list:
function getSum(num1: number, num2: number): number {
return num1 + num2;
}
To improve code quality and catch errors, consider enabling the following options in your TypeScript configuration file:
"noUnusedParameters": true
: Flags unused parameters in a function."noImplicitReturns": true
: Ensures that all code paths in a function explicitly return a value.
For more details, refer here.
What are your thoughts on this post?
I’d love to hear from you! Click this link to email me—I reply to every message!
Also use the share button below if you liked this post. It makes me smile, when I see it.