Bitpath

Lesson 1 · Unit 04

Boundaries

Data from outside is unknown until checked at run time

13 exercisesabout 3 min

What you practise

  • JSON.parse returns any
  • Validating unknown data
  • Type guards and assertion functions
  • What as promises and cannot check

Try a question from this lesson

Pick one

Throwback to narrowing with typeof. The check on line 2 narrows data. Is that enough for line 3?

TypeScript
function idOf(data: unknown): number {
  if (typeof data === "object") {
    return data.id;
  }
  return 0;
}

The ideas

Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.

Concept

The boundary

Inside your program the compiler has checked every value. Data from outside has been checked by no one: a network response, a file, user input, JSON.parse.

That edge is the boundary. The honest type for what crosses it is unknown, and the job there is to inspect the actual value at run time, and only then give it a type. Python has the same split: type hints say nothing about what json.loads returns.

TypeScript
const text = '{"id": "7"}';

const a = JSON.parse(text);   // any
const b: unknown = JSON.parse(text);

a.id.toFixed(0);  // compiles, crashes
// b.id;          // rejected: unknown

Concept

Type guards

A type guard is a function that inspects a value at run time and reports the result to the compiler. Its return type, v is string, is called a type predicate.

The compiler trusts the predicate completely. It does not check that the body tests what the signature claims, so a guard is only as good as its checks. Python's counterpart is TypeGuard, or isinstance for classes.

TypeScript
function isStr(v: unknown): v is string {
  return typeof v === "string";
}
const d: unknown = JSON.parse('"hi"');
if (isStr(d)) {
  d.toUpperCase(); // d is a string here
}

Concept

Assertion functions

A guard answers yes or no. An assertion function either returns or throws, and its return type says what is true if it returns: asserts v is User.

After the call, the rest of the scope sees the narrowed type, with no if. It is Python's assert isinstance(v, User), with one difference: this check is ordinary code and is never stripped out.

TypeScript
interface User { id: number }
function assertUser(
  v: unknown,
): asserts v is User {
  const ok = typeof v === "object"
    && v !== null && "id" in v
    && typeof v.id === "number";
  if (!ok) throw new Error("not a user");
}
const d: unknown = JSON.parse('{"id":7}');
assertUser(d);
console.log(d.id); // d is a User here

9 more exercises in the app

  • 4× type the answer
  • 2× fill the blanks
  • 1× order the lines
  • 1× multiple choice
  • 1× true or false

Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.

One email when Bitpath is ready to try. Nothing else. Privacy