Lesson 1 · Unit 04
Boundaries
Data from outside is unknown until checked at run time
What you practise
JSON.parsereturnsany- Validating unknown data
- Type guards and assertion functions
- What
aspromises 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?
function idOf(data: unknown): number {
if (typeof data === "object") {
return data.id;
}
return 0;
}Correct answer
No: data may be null, and id is not known
Why
typeof null is "object", so data is object | null here, and the type object promises no particular property. Three checks are needed: it is not null, it has an id, and the id is a number.
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.
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: unknownConcept
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.
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.
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 here9 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.