TypeScript Fundamentals: Types, Functions, and Objects
TypeScript Fundamentals: Types, Functions, and Objects
Introduction to TypeScript
TypeScript, developed by Microsoft, is a powerful addition to JavaScript, gaining increasing support from modern technologies like Angular, Vue.js 3, and React.js.
It compiles to ES5, incorporating all native JavaScript features such as spread, arrow functions, and deconstructors. TypeScript also introduces useful features like decorators, generics, interfaces, enums, and modules, found in other programming languages.
TypeScript enhances JavaScript with static typing and advanced features, compiling to standard ES5 for broad compatibility.
TypeScript: JS + Types & Advanced Features
Understanding TypeScript Types
To create useful programs, we need to work with basic data units like numbers, strings, and boolean values. TypeScript supports most JavaScript types, with the addition of a convenient enumeration type.
Basic Type Assignments
String Type
The string type is used for textual data, just like in other languages. TypeScript uses double quotes (") or single quotes (') to surround string data, mirroring JavaScript's flexibility.
const myName: string = 'Robert';
Number Type
All numbers in TypeScript are floating-point values and are assigned the number type. Beyond hexadecimal and decimal literals, TypeScript also supports binary and octal literals, introduced in ECMAScript 2015.
const myAge: number = 24;
Boolean Type
The boolean type represents simple true/false values, a fundamental datatype in both JavaScript and TypeScript.
const bHasHobbies: boolean = true;
Array Type
TypeScript allows working with arrays of values, similar to JavaScript. Array types can be declared by following the element type with [].
const hobbies: string[] = ['Programming', 'Cooking'];
If no types are explicitly declared, TypeScript will automatically infer a type based on the array's values. For example, const numbers = [1, 3.22, 6, -1] will be inferred as number[].
While TypeScript can infer array types, explicitly declaring them (e.g., string[]) is strongly encouraged for better type safety and code clarity.
Explicit array types improve safety.
Tuples
Tuple types enable you to define an array with a fixed number of elements where each element can have a different, known type. This is useful for representing structured data, like a pair of a string and a number.
const address: [string, number] = ["Street", 99];
Any Type
The any type is used for variables whose types are not known at the time of writing the application, often from dynamic content or third-party libraries. It allows opting out of type-checking for these values during compilation.
let myCar: any = 'BMW';
console.log(myCar); // Prints: BMW
myCar = { brand: 'BMW', series: 3 };
console.log(myCar) // Prints: { brand: "BMW", series: 3 }
The any type bypasses type-checking, offering flexibility for unknown types but sacrificing type safety. Use it judiciously.
any type: use sparingly.
Enums
Enums are a helpful addition to JavaScript's standard datatypes, providing friendly names to sets of numeric values, similar to C#. By default, enum members start numbering at 0, but you can manually set values for members, which will then influence subsequent members.
enum Color {
Gray, // 0
Red, // 1
Green = 100, // 100
Blue, // 101
Yellow = 2 // 2
const myColor: Color = Color.Green
console.log(myColor); // Prints: 100
Functions in TypeScript
Functions in TypeScript operate similarly to JavaScript, but with added type features. You can assign types to both function arguments and the function itself (its signature).
Argument Types
Any argument of a function in TypeScript can be assigned a type, regardless of its complexity, ensuring type-safe parameter passing.
function multiply(value1: number, value2: number) {
return value1 value2;
// console.log(multiply('Robert', 5)) // Not possible, both arguments must be of type number.
console.log(multiply(10,5)) // Prints: 50
Function Types
Just as arguments can be typed, the return value of a function can also be assigned a type. This defines the expected signature of a function variable.
const myMultiply: (val1: number, val2: number) => number;
// myMultiply = sayHello; // Not possible.
// myMultiply(); // Not possible.
myMultiply = multiply;
console.log(myMultiply(5, 2));
Void Function Type
The void type signifies the absence of any type, often used as the return type for functions that do not return a value. Declaring variables of type void is not practical, as they can only be assigned undefined or null.
function sayHello(): void {
console.log('Hello!');
// return myName; // Not possible because the function can't return anything due to the void assigned type (more on this below).
The void type is used for functions that explicitly do not return a value, ensuring that no return type is expected or used.
void means no return value.
Working with Objects
The object type represents non-primitive types—anything that is not a number, string, boolean, symbol, null, or undefined. In TypeScript, as in JavaScript, objects are composed of key-value pairs, and you can assign types to these pairs.
let userData: { name: string, age: number } = {
name: 'Max',
age: 27
// userData = { // Not valid
// name: 2,
// age: 'Age'
// };
// userData = { // Not valid
// a: 'Robert',
// b: 24
// };
userData = {
name: 'Robert',
age: 24
Complex Objects
The types assigned to object key-value pairs can be highly complex, allowing for detailed structuring of data and function signatures within an object.
let complex: { data: number[], output: (all: boolean) => number[] } = {
data: [100, 3,99, 10],
output: function(all: boolean): number[] {
return this.data
// complex = {}; // Not possible.
Optional Object Properties
In TypeScript, object properties (including function parameters and interface properties) can be declared as optional by placing a ? character after the property's key or name during declaration. This allows objects to omit these properties without causing type errors.
const right: { name: string, age?: number } = {
name: 'Robert'
const alsoRight: { name: string, age?: number } = {
name: 'Robert',
age: 24
// This is not possible because the name key-value pair is missing.
// const wrong: { name: string, age?: number } = {
// age: 24
// };
What is TypeScript?
A superset of JavaScript developed by Microsoft that adds static typing and other features.
What JavaScript features does TypeScript include?
All native JavaScript features like spread, arrow functions, and deconstructors.
Name some features TypeScript introduces.
Decorators, generics, interfaces, enums, and modules.
What are the basic data types in TypeScript?
Number, string, boolean, array, tuple, any, enum, object, void.
How do you declare a string variable in TypeScript?
const myName: string = 'Robert';
What type are all numbers in TypeScript?
Floating point values.
How can you declare an array of strings?
const hobbies: string[] = ['Programming', 'Cooking'];
What is a Tuple type used for?
To express an array where the type of a fixed number of elements is known, but need not be the same (e.g., [string, number]).
When would you use the any type?
When the type of a variable is unknown at compile time, often from dynamic content, to opt-out of type-checking.
What is an enum in TypeScript?
A way of giving more friendly names to sets of numeric values.
How do enums typically start numbering their members?
By default, they start at 0.
How can you assign types to function arguments?
function multiply(value1: number, value2: number) { ... }
How can you define a function type for a variable?
const myMultiply: (val1: number, val2: number) => number;
What does the void type signify for a function?
That the function does not return any value.
What does the object type represent in TypeScript?
Non-primitive types (anything not number, string, boolean, symbol, null, or undefined).
How do you declare an optional property in a TypeScript object type?
By placing a ? after the property name, e.g., { name: string, age?: number }.