Mastering TypeScript: Type Declarations, Type Assertions, and Non-null Assertions

Types can be assigned to variables and values in TypeScript by using Type Declarations, Type Assertions, and Non-null Assertions to help declare and enforce the type of a variable. Let’s go over each one with some examples:

Type Declaration:

Type declarations allow you to specify the type of a variable explicitly. TypeScript will verify and ensure that the variable is of this type.

let age: number;
age = 25; // Valid assignment
// age = "25"; // Error: Type '"25"' is not assignable to type 'number'.

In this example, we declare a variable age and state that its type is integer explicitly. TypeScript will ensure that it only receives numeric data.

Some more example:

Arrays with specific element types:
let numbers: number[] = [1, 2, 3, 4, 5];
let names: string[] = ["Alice", "Bob", "Charlie"];

Object properties with specified types:
let person: { name: string; age: number } = {
name: "John",
age: 30,
};

Type Assertion:

Type assertions, also known as type casting, allow you to tell TypeScript that you know more about the type of a value than it does. It allows you to temporarily override TypeScript’s type inference.

let value: any = "Hello, TypeScript!";
let length: number = (value as string).length;

console.log(length); // Output: 16

We use a type assertion (value as string) to warn TypeScript that we’re treating value as a string, despite the fact that its type is any.

Some More Example:

Type assertion with the as keyword:
let value: any = "Hello, TypeScript!";
let length: number = (value as string).length;

Type assertion for handling JSON data:
let jsonString = '{"name": "Alice", "age": 25}';
let data = JSON.parse(jsonString) as { name: string; age: number };
console.log(data.name); // "Alice"

Non-null Assertion:

A non-null assertion (!) tells TypeScript that you are certain a variable will not be null or undefined, even if the type system would ordinarily consider it nullable.

let username: string | null = getUsernameFromAPI();
let length: number = username!.length;

console.log(length); // Output: Error if username is null, otherwise the length

In this case, username is declared as a string | null, implying that it can be either a string or null. The non-null assertion! tells TypeScript that we are certain that username will not be null when we access its length attribute. However, if getUsernameFromAPI returns null, a runtime error will occur.

Some Example:

Asserting non-nullability with !:
let username: string | null = getUsernameFromAPI();
let length: number = username!.length; // Assuming username is not null

Asserting non-nullability with optional chaining and the nullish coalescing operator:
let username: string | null = getUsernameFromAPI();
let length: number = username?.length ?? 0; // Safely handle null value

Using non-null assertions with functions that assert non-nullability:
function getNonNullUsername(): string {
let username: string | null = getUsernameFromAPI();
return username!; // Guaranteed non-null
}

These ideas are critical in TypeScript for ensuring type safety and assisting the compiler in detecting type-related problems during development.

You can also discover a lot about git by exploring different topics.

Note: We welcome your feedback at Easy Coding School. Please don’t hesitate to share your suggestions or any issues you might have with the article!

Leave a Reply

Your email address will not be published. Required fields are marked *