

0 / 2 embers
0 / 3000 xp
click for more info
Complete a lesson to start your streak
click for more info
Still calibrating
click for more info
Not enough gems
Cost: 6 gems
1: Narrowing Types
incomplete
2: Unknown Type
incomplete
3: Type Hierarchy
incomplete
4: Narrowing Using In
incomplete
5: Type Predicates
incomplete
6: Exhaustive Checks
incomplete
7: Guard Clauses
incomplete
8: Type Assertion
incomplete
9: Double Assertion
incomplete
10: Non-Null Assertion
incomplete
Back
ctrl+,
Next
ctrl+.
This lesson's interactive features are locked, please to keep using them
Sometimes the built-in type guards (typeof, instanceof, etc.) aren't enough.
TypeScript allows you to create your own type guards using type predicates. We do that by creating a function that:
value is Type in the return typeFor example, here's a function that reports if a value is a string:
function isString(value: unknown): value is string {
return typeof value === "string";
}
function processValue(value: unknown) {
if (isString(value)) {
// TypeScript knows value is a string here
console.log(value.toUpperCase());
}
}
For simple stuff like this, we could have just inlined the typeof check:
function processValue(value: unknown) {
if (typeof value === "string") {
// TypeScript knows value is a string here
console.log(value.toUpperCase());
}
}
But type predicates become really useful when the logic to check the type is a bit more complex. So we have a situation where one type, in this case, the ManagerAdmin type, shares properties with both other types:
interface ManagerAdmin {
accessLevel: number;
numEmployees: number;
}
interface Admin {
accessLevel: number;
payrollDate: Date;
}
interface Manager {
numEmployees: number;
}
We can encapsulate the slightly more complex logic in a type predicate function:
function isManagerAdmin(
boss: ManagerAdmin | Admin | Manager,
): boss is ManagerAdmin {
return "numEmployees" in boss && "accessLevel" in boss;
}
// boss is a `ManagerAdmin | Admin | Manager`
if (isManagerAdmin(boss)) {
// TypeScript knows boss is a ManagerAdmin here
console.log(`Managing ${boss.numEmployees} employees`);
}
We support multiple LLMs, those per-token prices aren't gonna arbitrage themselves...
Anyhow, we need to write code to activate a specific model when starting a chat with a customer.
{VERSION} is simply the version property{STATUS} is either enabled or disabled based on the search property{VERSION} is simply the version property{STATUS} is either enabled or disabled based on the think property