Table of contents
1.
Introduction
2.
What is TypeScript?
3.
Different types of keywords in TypeScript
3.1.
'this' Keyword
3.2.
Function Declaration Keywords
3.3.
Data Type Keywords
3.4.
Variable Declaration Keywords
4.
“As” Keyword in TypeScript
5.
Types of type assertions
6.
Frequently Asked Questions
6.1.
When to use the "as" keyword?
6.2.
How does the "as" keyword work?
6.3.
What happens if I use "as" with the wrong type?
7.
Conclusion
Last Updated: Mar 27, 2024
Easy

TypeScript "as" Keyword

Author Arya Singh
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Microsoft developed and continues to maintain TypeScript, a programming language and a robust open-source superior set of Javascript. It helps to create massive rich, sustainable applications by enhancing the Javacript's syntax with extra features like static typing, Object-Oriented programming, Type Inference, Code maintainability, Language Evolution, etc., improving JavaScript with security, enhanced code maintenance, and better tooling.

TypeScript "as" Keyword

This article contains information on Typescripts and explains some keywords used in it, highlighting “as” keyword.

What is TypeScript?

TypeScript is a programming language that makes writing code for web applications easier and less error-prone. It's like JavaScript, but with extra superpowers! TypeScript helps developers catch mistakes early by checking for errors while writing code. This reduces bugs and makes it simpler to work with large projects. It also adds features not available in JavaScript, such as strong typing, which allows developers to define the types of variables, making code more reliable. TypeScript also supports modern JavaScript features and can be used with any web browser or platform. Overall, TypeScript is a helpful tool for web developers, making their coding experience smoother and more efficient.

Different types of keywords in TypeScript

'this' Keyword

'this' is a unique keyword representing the current instance of an object in a method.

Example:

class Person {
 constructor(private name: string) {}
 greet() {
   // 'this' refers to the current instance of the 'Person' class.
   console.log("Hello, my name is " + this.name);  
 }
}


These are some of the essential types of keywords in TypeScript, each serving a specific purpose in the language to help you define and control your code effectively.

Function Declaration Keywords

Keywords used to define functions in TypeScript.

Example:

function add(a: number, b: number): number {
 return a + b;
}

Data Type Keywords

Data type keywords help define the type of variables or values in TypeScript.

Example:

// 'number' is the data type keyword here, indicating the variable 'age' holds a number value.
let age: number = 30; 
// 'string' is the data type keyword, declaring the variable 'name' 
let name: string = "John"; 

Variable Declaration Keywords

These keywords are used to declare variables in TypeScript.

Example:

// 'let' is the variable declaration keyword, creating a variable named 'message'.
let message: string = "Hello TypeScript!";
// 'const' declares a constant variable named 'PI'. 
const PI: number = 3.14; 

“As” Keyword in TypeScript

The "as" keyword is an essential part of Typescript for type assertions (type casting) and narrowing. It informs the compiler to consider a value of a particular type if the compiler fails to know its kind. It grants coders greater power in type checking and helps to maintain the disparity between dynamic code and static typing. It is beneficial in dealing with intricate data structures or instances where TypeScript's type detection is incorrect.

For instance, when working with JavaScript libraries or external data, TypeScript may not accurately determine the types. The "as" keyword lets you manually assert the type and avoid unnecessary type-checking errors.

Here's an example:

// Suppose we have some data coming from an API or external source
const data: unknown = {
 name: "John",
 age: 30,
};
// Without type assertion, TypeScript would raise an error here
// because it doesn't know the exact type of 'data'

const nameLength = (data.name as string).length;
const ageAfterFiveYears = (data.age as number) + 5;
console.log(`Name length: ${nameLength}`);
console.log(`Age after five years: ${ageAfterFiveYears}`);


In the code above, we use "as" to explicitly tell TypeScript that 'data.name' is a string and 'data.age' is a number. This way, TypeScript won't show errors, and we can perform operations without worries.

Types of type assertions

1.  Variable as Type:

This type specifies the type of the variable or the expression.

Syntax

let someValue: unknown = "Hello, TypeScript!";
let strLength: number = (someValue as string).length;


2. JSX Elements Type Assertions: 

The angle-bracket syntax is utilized when using JSX in TypeScript for JSX-type assertions.

Syntax

let anotherValue: unknown = "Hello, again!";
let strLength: number = (<string>anotherValue).length;

Although Type assertion is an excellent tool, it is not without hazards and aspects.

Improper type assertions might create runtime bugs, so being particular about real type values is essential.

TypeScript will blindly trust the developer's assertion. If the assertion is erroneous, type-related problems may not be recognized until later. Type assertions should be used only when necessary. Use TypeScript's type inference system or explicit annotations whenever possible to ensure type safety and maintainability.

Frequently Asked Questions

When to use the "as" keyword?

When confident about the value type, you should use the "as" keyword, but TypeScript's type inference system cannot determine it. It helps avoid type-checking errors and enables you to access properties or methods specific to that type.

How does the "as" keyword work?

When you use the "as" keyword, you tell TypeScript about what type of value it is. This way, TypeScript will trust your assertion and allow you to work with the value as if it were of that specific type.

What happens if I use "as" with the wrong type?

If you incorrectly assert a type using "as," TypeScript won't catch the error during compilation. However, if the value's actual type does not match the asserted type, you may encounter runtime errors or unexpected behavior.

Conclusion

This article explains what typescript is and the different keywords in typescript. It also mainly focuses on the “as” keyword in typescript. We hope this blog has helped you enhance your knowledge of Deploying apps with Express js. If you want to learn more, then check out our articles.


You may refer to our Guided Path on Code Studios for enhancing your skill set on DSA, Competitive Programming, System Design, etc. Check out essential interview questions, practice our available mock tests, look at the interview bundle for interview preparations, and so much more!

Happy Learning!

Live masterclass