as keyword
- TypeScript course
- Intermediate
- Lesson 66/89
- 4 min
Learn type assertion with as.
What is the as keyword?
The as keyword is used for type assertion in TypeScript. You tell the compiler that a value is of a specific type; this does not change the value at runtime, it is only compile-time information. It is commonly used to narrow any or unknown values to a more specific type.
let value: any = "hello";
const length = (value as string).length;When to use as?
as is typically used to explicitly state a type the compiler cannot infer. For example, when you want to treat a DOM element as an HTMLInputElement. It is also common for safely casting an unknown value to a specific type.
const input = document.getElementById("name") as HTMLInputElement;
console.log(input.value);Practice String length with as
The deger variable is of type any with value "merhaba". Use as to assert it as string and print its .length property with console.log.
Starter code
// deger degiskenini string olarak isaretle
// sonra uzunlugunu yazdir
const deger: any = "merhaba";Sample solution
const deger: any = "merhaba";
const metin = deger as string;
console.log(metin.length);Expected output
7
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What is the runtime effect of the as keyword?
- No effect, works only at compile time Correct answer
- Converts the value to a new type
- Permanently changes the variable's type
- Creates a new variable
Explanation: as is compile-time only; it does not change the value at runtime at all.
2 Assert as string with as
const deger: any = "merhaba";
const metin = deger ____ string;
console.log(metin.length);
const deger: any = "merhaba";
const metin = deger as string;
console.log(metin.length);
Explanation: The as keyword tells the compiler the value is of type string.
3 as usage
| Term | Meaning |
|---|---|
as |
Type assertion keyword |
derleme zamanı |
Assertion works here |
çalışma zamanı |
Value unchanged |
any |
Unsafe base type |