This blog post is about type assertions in TypeScript, which are related to type casts in other languages and performed via the as
operator.
Table of contents:
A type assertion lets us override a static type that TypeScript has computed for a storage location. That is useful for working around limitations of the type system.
Type assertions are related to type casts in other languages, but they don’t throw exceptions and don’t do anything at runtime (they do perform a few minimal checks statically).
const data: object = ['a', 'b', 'c']; // (A)
// @ts-ignore: Property 'length' does not exist on type 'object'.
data.length; // (B)
assert.equal(
(data as Array<string>).length, 3); // (C)
object
.as
) to tell TypeScript that data
is an Array. Now we can access property .length
.#typescript #javascript