Advanced TypeScript Concepts
Union Types
Union types allow you to define a variable that can hold multiple types. This is useful when a variable or parameter can accept values of different types.
Example:
function combine(input1: number | string | boolean, input2: string) {
const result = input1 + input2;
return result;
}
combine(30, "26"); // Error because input2 is not a string
combine("Hello", " World"); // Works fine
In this example, input1
can be a number, string, or boolean, while input2
must be a string. This flexibility allows the function to handle different types of inputs.
Another Example:
let myName: string | null = null;
myName = "test"; // No error
Here, myName
can be a string or null, providing more flexibility in type assignments.
Literal Types
Literal types allow you to specify exact values a variable can have. This is useful for creating strict types with limited allowed values.
Example:
function combine(input1: number | string, input2: number | string, resultConversion: 'as-number' | 'as-text') {
// function body
}
// resultConversion can only be 'as-number' or 'as-text'
In this example, resultConversion
can only take the values 'as-number'
or 'as-text'
, ensuring that only these specific values are used.
Type Aliases
Type aliases allow you to create a new name for an existing type or a combination of types. This can make your code more readable and maintainable.
Example:
type Combinable = number | string;
type ConversionDescriptor = 'as-number' | 'as-string';
function combine(input1: Combinable, input2: Combinable, resultConversion: ConversionDescriptor) {
// function body
}
Here, Combinable
and ConversionDescriptor
are type aliases that simplify the function definition and make it more readable.
Function Return Types
Specifying return types for functions helps TypeScript infer the correct types and catch errors early.
Example:
function add(n1: number, n2: number): number {
return n1 + n2;
}
function addWithError(n1: number, n2: number): string {
return n1 + n2; // Error: Type 'number' is not assignable to type 'string'
}
function logResult(n1: number, n2: number): void {
console.log(n1 + n2);
}
function returnUndefined(n1: number, n2: number): undefined {
console.log(n1 + n2);
return; // Error: Type 'void' is not assignable to type 'undefined'
}
In these examples, we see functions with return types number
, string
, void
, and undefined
. The void
return type is used when the function does not return anything.
Functions as Types
You can specify a variable as a function type to ensure it only holds functions.
Example:
function add(n1: number, n2: number): number {
return n1 + n2;
}
let myFunc: (a: number, b: number) => number;
myFunc = add;
myFunc = 5; // Error: Type 'number' is not assignable to type '(a: number, b: number) => number'
console.log(myFunc(8, 8)); // Works fine
Here, myFunc
is explicitly typed as a function that takes two number
arguments and returns a number
.
Defining Callback Types
You can define the type of a callback function parameter to ensure the callback is used correctly.
Example:
function addAndHandle(n1: number, n2: number, cb: (num: number) => void) {
const result = n1 + n2;
cb(result);
}
In this example, cb
is a callback function that takes a number
argument and returns void
.
Unknown Type
The unknown
type is a safer alternative to any
because it forces type checking before assignments.
Example:
let userInput: unknown;
userInput = 5;
userInput = 'Sufiyan';
let userName: string;
// userName = userInput; // Error: Type 'unknown' is not assignable to type 'string'
if (typeof userInput === 'string') {
userName = userInput; // Works fine
}
The unknown
type requires type checks before assigning its value to another variable.
Never Type
The never
type represents values that never occur, typically used for functions that never return.
Example:
function generateError(message: string, code: number): never {
throw { message: message, errorCode: code };
}
const result = generateError('Wrong Credentials', 500);
console.log(result); // This line will never execute
Functions with the never
return type indicate that they never successfully complete.
This documentation covers Union types, Literal types, Type Aliases, Function Return Types, Functions as Types, Callback Types, the Unknown Type, and the Never Type in TypeScript.