I was working on a TypeScript project that required handling data from a third-party API. TypeScript doesn’t always know the exact type of a variable, especially when dealing with external APIs or complex data structures. Without defining the data, I was getting errors because we need a way to tell TypeScript about the type we expect.
As a solution, I used the type assertion with the ‘as’ keyword in TypeScript. In TypeScript, the as keyword is used to tell the compiler what type a value should be. This type of assertion helps avoid type errors and makes the code easier to work with.
In this article, I’ll explain about the ‘as’ keyword in TypeScript, how it works, why it’s useful, and the different ways you can apply it for assertions.
What is the ‘as’ Keyword in TypeScript?
The as keyword in TypeScript is used for type assertions. It tells the TypeScript compiler to treat a value as a specific type, regardless of what TypeScript might infer on its own.
Type assertions are particularly useful when:
- Working with data from external sources
- Converting between compatible types
- Working with DOM elements
- Dealing with complex data structures
Method 1: Basic Type Assertion Using ‘as’
The most common use of the as keyword is to assert a specific type for a variable. Let’s see how this works:
function getUserInput(): any {
return "Andrew";
}
// Use 'as' to assert the type
const userInput = getUserInput() as string;
// Now TypeScript treats it as a string
console.log(userInput.toUpperCase()); // Output: ANDREWOutput:

In this example, TypeScript now treats userInput as a string, allowing us to use string methods without compiler warnings.
Check out: Index Signature in TypeScript
Method 2: Type Assertion vs Type Casting
It’s important to understand that ‘as‘ keyword doesn’t actually change the runtime type of a variable it just tells TypeScript to treat it as a specific type.
// This works in TypeScript compilation
const value: any = "42";
const numValue = value as number;
// But at runtime, numValue is still a string!
// This will output "4242" not 84
console.log(numValue + numValue);Output:

This is different from type casting in languages like C# or Java, where the value would actually be converted.
Method 3: Using ‘as’ with DOM Elements
When working with the DOM, as is incredibly helpful for specifying element types:
// TypeScript only knows this is some kind of HTMLElement
const submitButton = document.getElementById('submit');
// We assert it's specifically a button element
const button = submitButton as HTMLButtonElement;
// Now we can access button-specific properties
button.disabled = true;Without the assertion, TypeScript wouldn’t know that the element has the disabled property.
Check out: Spread Operator in TypeScript
Method 4: Chaining ‘as’ Assertions
Sometimes you need to make multiple type assertions in sequence:
// Starting with an unknown type
const data: unknown = fetchUserData();
// First assert it's an object
const userObject = data as object;
// Then assert it's our specific user type
const user = userObject as User;
// Now we can access User properties
console.log(user.firstName);Output:

Check out: Initialize Maps in TypeScript
Method 5: The ‘as const’ Assertion
A special use of the as keyword is with const, which creates a readonly type:
// Normal array - elements can be changed
const states = ["New York", "California", "Texas"];
// With 'as const' - creates a readonly tuple type
const readonlyStates = ["New York", "California", "Texas"] as const;
// This is allowed
states[0] = "Florida";
// This gives a TypeScript error
readonlyStates[0] = "Florida"; // Error: Cannot assign to '0' because it is a read-only propertyValid Output:

Invalid Output:

This is particularly useful for creating immutable data structures.
Check out: Check the Type of a Variable in TypeScript
Method 6: Using ‘as’ with Union Types
When dealing with union types, as can help narrow down the specific type:
// Define types
type CreditCard = {
type: 'credit';
cardNumber: string;
expiryDate: string;
};
type PayPal = {
type: 'paypal';
email: string;
};
type BankTransfer = {
type: 'bank';
accountNumber: string;
bankCode: string;
};
type PaymentMethod = CreditCard | PayPal | BankTransfer;
// Type guard for PayPal
function isPayPal(payment: PaymentMethod): payment is PayPal {
return payment.type === 'paypal';
}
// Process payment
function processPayment(payment: PaymentMethod) {
if (isPayPal(payment)) {
console.log("Processing PayPal payment for:", payment.email);
} else {
console.log("Not a PayPal payment.");
}
}
// Call with a sample PayPal payment
const payment: PaymentMethod = {
type: 'paypal',
email: 'user@example.com',
};
processPayment(payment);Output:

Method 7: The Angle Bracket Syntax Alternative
Before as became standard, TypeScript used angle brackets for type assertions:
// Old syntax using angle brackets
const button = <HTMLButtonElement>document.getElementById('submit');
// New syntax using 'as'
const buttonAs = document.getElementById('submit') as HTMLButtonElement;Both do the same thing, but the as syntax is preferred in modern TypeScript, especially when working with JSX/TSX files, where angle brackets could be confused with React components.
Type Assertion Safety
It’s important to use type assertions responsibly. TypeScript will only allow assertions between compatible types:
// Original string value
const value: string = "42";
console.log("Original string value:", value); // "42"
const numValue = value as unknown as number;
console.log("After double assertion (string -> number):", numValue); // "42"
console.log("typeof numValue:", typeof numValue); // "string" still a string at runtime
const fakeDateValue = value as unknown as Date;
console.log("After double assertion (string -> Date):", fakeDateValue); // Still just a string
const actualDate = new Date(value);
console.log("Properly converted to Date:", actualDate); // Valid Date objectOutput:

For completely incompatible types, you need to use unknown as an intermediate step.
Type assertions should be used sparingly and only when you’re certain about the actual type. Overusing them can defeat the purpose of TypeScript’s type checking.
I hope you found this article helpful. The as keyword is a powerful tool in TypeScript that, when used correctly, can make your code more expressive and type-safe. It’s especially useful when working with external data sources or when TypeScript’s type inference needs a little help.

I am Bijay Kumar, a Microsoft MVP in SharePoint. Apart from SharePoint, I started working on Python, Machine learning, and artificial intelligence for the last 5 years. During this time I got expertise in various Python libraries also like Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… for various clients in the United States, Canada, the United Kingdom, Australia, New Zealand, etc. Check out my profile.