Skip to content
Search

TypeScript:asserts

lastmod 2022-04-11created 2022-04-053 edits

About the asserts syntax in TypeScript.

Intro

There is a set of functions that throw an error if something unexpected happens. They are called "assertion" functions.

For example, Node.js has a dedicated function for this called assert.

For example:

function multiply(x, y) {
  assert(typeof x === "number");
  assert(typeof y === "number");
  return x * y;
}

Unfortunately, in TypeScript these checks could never be properly encoded.

  • For loosely-typed code, TypeScript was checking less,
  • and for slightly conservative code, it often forced users to use type assertions.

The alternative is to rewrite the code so the language can analyze it instead, but this is not convenient:

function yell(str) {
  if (typeof str !== "string") {
    throw new TypeError("str should have been a string.");
  }
  // Error caught!
  return str.toUppercase();
}

Ultimately, TypeScript's goal is to type existing JavaScript constructs in the least disruptive way. For that reason, TypeScript 3.7 introduced a new concept called "assertion signatures" that models these assertion functions.

The first type of assertion signature models the way Node's assert function works. It ensures that whatever condition is being checked must be true for the rest of the containing scope.

function assert(condition: any, msg?: string): asserts condition {
  if (!condition) {
    throw new AssertionError(msg);
  }
}

The other type of assertion signature doesn't check for a condition, but instead tells TypeScript that a specific variable or property has a different type.

function assertIsString(val: any): asserts val is string {
  if (typeof val !== "string") {
    throw new AssertionError("Not a string!");
  }
}

It can also be expressed with generics:

function assertIsDefined<T>(val: T): asserts val is NonNullable<T> {
  if (val === undefined || val === null) {
    throw new AssertionError(
      `Expected 'val' to be defined, but received ${val}`
    );
  }
}

IntelliJ type hint constraints

Note that this approach can be used to constrain type hints in IntelliJ-family IDEs.

Teyp Assertion

IntelliJ type hints can also be constrained using type assertions.

Angle bracket

An angle bracket is a type wrapped in < and >.

let assertion:any = "타입 어설션은 '타입을 단언'합니다.";

// 방법 1: assertion 변수의 타입을 string으로 단언 처리
let assertion_count:number = (<string>assertion).length;

as syntax

let assertion:any = "타입 어설션은 '타입을 단언'합니다.";

// 방법 2: assertion 변수의 타입을 string으로 단언 처리
let assertion_count:number = (assertion as string).length;

JSX constraint

Both methods above give the same result. However, when used with JSX, only the as syntax is allowed.

See also

Favorite site

author Zer0 sitemap