

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
We've talked about the any type in TypeScript, and how it can represent anything - it's the "widest" type.
The unknown type can be used for similar purposes, but it's a much safer alternative because it forces you to explicitly assert the type before using it in a specific way.
The any type basically turns off TypeScript's type checking:
function processData(data: any) {
// TypeScript allows this even though it might crash
console.log(data.toLowerCase());
// TypeScript allows this too - it's like we're using plain JavaScript
return data.nonExistentMethod();
}
// No errors when calling the function
processData(42); // Will crash at runtime
As we talked about earlier, when you take plain JavaScript code and run it through TypeScript tooling, almost everything is any by default.
The unknown type doesn't allow that kind of tomfoolery:
function processData(data: unknown) {
// Error: Object is of type 'unknown'
console.log(data.toLowerCase());
// Error: Object is of type 'unknown'
return data.nonExistentMethod();
}
With unknown, you can still assign any value to it (e.g. call this function with any value), but you can't use that value in a meaningful way without first checking its type:
function processData(data: unknown) {
// We do a type assertion
if (typeof data === "string") {
// Now TypeScript knows data is a string
console.log(data.toLowerCase());
return data;
}
if (typeof data === "number") {
// Now TypeScript knows data is a number
return data * 2;
}
// Throw an error for other types
// that we can't handle
throw new Error("Expected string data");
}
unknownUnknown is a fantastic alternative to any when it comes to dealing with values that are coming into your program from the outside world (e.g. user input, API responses, etc.). It forces you to add type checks at that I/O boundary so that you can then be confident working with the data inside your program.
Support.ai needs a robust message parser that can handle email inputs, which are received as strings, or chat inputs, which are received as arrays of strings.
Complete the parseCustomerMessage function. It receives an unknown input and returns a CustomerMessage:
Use Array.isArray() to check if an input is an array.