Typescript type assertion

Author: Dawid Adach

-

During application development, it may happen that you deal with a situation where you will know more about the value than TypeScript does. Most often in a situation, where you know that the type of a certain entity could be more specific than it is now.

Type assertion is a way to explicitly inform the compiler that you want to treat the entity as it would have a different type. This allows you to treat any as a number, or a number as a string. Let's have a look at the following example:

let someValue: any = "I am sure I am a string";

Although, we are sure that someValue contains a string, for the compiler it still has a type of any. As result, you won't be able to use methods like length() which is a default method for a string type variable. What you can do is to inform the compiler to treat it as a string. You can do this in two ways:

let strLength: number = (someValue).length;

Or using the as syntax:

let strLength: number = (someValue as string).length;

Rate this lesson

Previous lesson Next lesson

Spread the word:
Do you need help? Use our support forum

About the author

Dawid Adach
For more than 5 years Dawid worked as an IT Consultant specializing in SOA/EAI/ESB in the banking domain. He gained experience working in countries like Netherlands, Belgium, Poland and India developing enterprise-class systems for the most prestigious companies. Since co-founding mdbootstrap.com & brandflow.net in 2016 he has been using and teaching technologies such as Angular, TypeScript, PHP, AJAX, Mongo, SQL, Hadoop Stack, Virtualization, Automation and many others...

Install MDB CLI
It's the fastest way to create and host MDB projects
Free Download

Sign up to follow your progress and get additional benefits