Suggest an editImprove this articleRefine the answer for “Type assertion (as)”. Your changes go to moderation before they’re published.Approval requiredContentWhat you’re changing🇺🇸EN🇺🇦UAPreviewTitle (EN)Short answer (EN)The **`as`** operator tells the compiler "I am sure this object has the specified type - just trust me", which effectively turns off type checking at that spot. **Key point:** overusing `as` hides real errors and breaks type safety, so instead you should narrow the variable's type, use type guards, or use `satisfies`.Shown above the full answer for quick recall.Answer (EN)Image## What `as` does The `as` operator tells the compiler: > "I am **sure** this object has the specified type - just trust me." Example: ```javascript const value: unknown = "hello"; const length = (value as string).length; // asserting that value is a string ``` Sometimes this is useful when TypeScript cannot infer the type on its own. --- ## Why overusing `as` is an antipattern The problem is that `as` **turns off type safety**. If you use it too often, you effectively **give up on type checking**, and TypeScript turns into plain JavaScript with nice highlighting. --- ## 1. `as` can hide real errors ```javascript type User = { name: string; age: number }; const data = { name: "Tim" } as User; // No error here console.log(data.age + 1); // Runtime error: age is undefined ``` Here TypeScript *took your word for it*, even though the object **does not match the type** `User`. Without `as`, the compiler would have warned: > Property 'age' is missing in type '{ name: string }' but required in type 'User'. --- ## 2. Breaking the real shape of the data ```javascript interface Animal { sound: string } interface Car { wheels: number } const myCar = { wheels: 4 } as Animal; // "tricking" the compiler console.log(myCar.sound.toUpperCase()); // a runtime error ``` > "as" just made the compiler believe the object is an Animal, > when in reality it is a car with no `sound` field. --- ## 3. The point of the type system is lost If you abuse `as`, TypeScript stops doing its main job: **preventing errors before the code runs.** An example from a real project: ```javascript (fetchData() as any).map(...) ``` Such code compiles, but it can throw a runtime error if `fetchData()` returns `null`, an `object`, or anything else. --- ## 4. `as` is often used because of poor type design When a developer does not want to deal with types, they write: ```javascript (someValue as any).doSomething(); ``` Instead of: narrowing the variable's type, adding a generic, using a type guard (`if ("prop" in value)`), or clarifying the function's return type. TypeScript specifically requires you to **clarify** types so the code is more reliable, and `as` bypasses that rule. --- ## 5. "Double assertion" (`as unknown as T`) is especially dangerous ```javascript const user = { name: "Tim" } as unknown as number; // Nonsense, but TS does not complain ``` > This is called the **double casting hack**: > you convert the value to `unknown`, then to any type you want. > TypeScript stops protecting you. --- ## When `as` is actually justified Using `as` is acceptable in **rare, controlled situations**: ### 1. In DOM manipulation: ```javascript const input = document.querySelector("input") as HTMLInputElement; input.value = "Hello"; ``` TypeScript does not know the element's exact type, but you do. ### 2. When working with generic functions and JSON: ```javascript const data = JSON.parse('{"id":1,"name":"Tim"}') as { id: number; name: string }; ``` The compiler cannot infer the type from a string. ### 3. In libraries/frameworks with dynamic typing (React refs, a Zustand store): ```javascript const ref = useRef() as React.MutableRefObject<HTMLDivElement | null>; ``` > The key is to **understand why the type is not inferred**, > and to use `as` deliberately, not as a "patch". --- ## How to avoid overusing `as` | Problem | Use this instead of `as` | |---|---| | TypeScript does not know the type | Narrow the variable's type at declaration | | You need a runtime type check | Use **type guards** (`typeof`, `instanceof`, `"key" in obj`) | | The type is too broad (`unknown`, `any`) | Extend the interface or add a generic | | You need a temporary check | Use `satisfies` (TS 4.9+) | ### Example: `satisfies` instead of `as` ```javascript const user = { name: "Tim", age: 25, } satisfies { name: string; age: number }; ``` > Checks the type at compile time > Does not change the value's type > Safer than `as` --- ## Summary | Benefits of `as` | Downsides of overusing it | |---|---| | Helps when TS cannot infer the type | Turns off type checking | | Useful in specific cases (DOM, JSON) | Masks errors and breaks safety | | A quick "crutch" when migrating to TS | Turns the code back into "JS without checking" | | Can be combined with `satisfies` | A double cast (`as unknown as T`) is dangerous |For the reviewerNote to the moderator (optional)Visible only to the moderator. Helps review go faster.