TypeScript · Beginner · 10 min
Checking unknown input
Use runtime checks before trusting data that comes from outside typed code.
Start with unknown
unknown requires a check before specific operations. Unlike any, it keeps type checking active at the point where the value is used.
function label(value: unknown): string {
return typeof value === "string" ? value.trim() : "Invalid";
}
console.log(label(" Ada "));Output
Ada
Check parsed data
JSON.parse() does not validate an application shape. Assign its result to unknown, then check the required property before reading it. A type assertion alone does not validate data.
const value: unknown = JSON.parse('{"name":"Ada"}');
if (typeof value === "object" && value !== null && "name" in value && typeof value.name === "string") {
console.log(value.name);
}Output
Ada
Try it yourself
Code runs on this device. When you are signed in, drafts sync to your account.
Check before reading a string
Make "label" trim a string and return "Invalid" for other inputs. Display the result for 4.
Use typeof to check whether "value" is a string.
Put it into practice
- Read the types and predict the output before running the examples.
- Complete the task, then check your understanding with the practice questions.