From 5cf7aa340f59f6f880e9a2b20af266a269c7c2ed Mon Sep 17 00:00:00 2001 From: Komal Shehzadi Date: Thu, 11 Jan 2024 11:11:38 +0500 Subject: [PATCH] Correction in as type operator example (#5017) --- .../115-type-assertions/101-as-type.md | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/src/data/roadmaps/typescript/content/101-typescript-types/115-type-assertions/101-as-type.md b/src/data/roadmaps/typescript/content/101-typescript-types/115-type-assertions/101-as-type.md index 94d892f49..85c2c5808 100644 --- a/src/data/roadmaps/typescript/content/101-typescript-types/115-type-assertions/101-as-type.md +++ b/src/data/roadmaps/typescript/content/101-typescript-types/115-type-assertions/101-as-type.md @@ -1,16 +1,18 @@ # As Type -as is a type assertion in TypeScript that allows you to tell the compiler to treat a value as a specific type, regardless of its inferred type. -For example: +In TypeScript, the as keyword is used for type assertions, allowing you to explicitly inform the compiler about the type of a value when it cannot be inferred automatically. Type assertions are a way to override the default static type-checking behavior and tell the compiler that you know more about the type of a particular expression than it does. + +Here's a simple example: ```typescript -let num = 42; -let str = num as string; +let someValue: any = "Hello, TypeScript!"; +let strLength: number = (someValue as string).length; -// str is now of type string, even though num is a number +console.log(strLength); // Outputs: 20 ``` +In this example, someValue is initially of type any, and we use the as operator to assert that it is of type string before accessing its length property. It's important to note that type assertions do not change the underlying runtime representation; they are a compile-time construct used for static type checking in TypeScript. It's important to note that type assertions do not change the runtime type of a value, and do not cause any type of conversion. They simply provide a way for the programmer to override the type inference performed by the compiler. -- [Type assertions](https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#type-assertions) \ No newline at end of file +- [Type assertions](https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#type-assertions)