Menu
Coddy logo textTech

The 'unknown' Type

Part of the Introduction To TypeScript section of Coddy's JavaScript journey — lesson 8 of 73.

Like any, a variable of type unknown can hold any value:

let userInput: unknown = "Hello";
userInput = 42;        // No error
userInput = true;      // No error

The key difference is that TypeScript won't let you perform operations on an unknown value without first checking what type it actually is. This prevents many runtime errors:

let data: unknown = "TypeScript";
// data.toUpperCase(); // Error! TypeScript doesn't know it's a string

// You must check the type first
if (typeof data === "string") {
    console.log(data.toUpperCase()); // Now it's safe!
}

This makes unknown much safer than any because it forces you to verify the type before using type-specific methods or properties.

quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

challenge icon

Challenge

Easy

Create a variable named userInput with the type unknown and assign it the string "TypeScript".

Then write a type guard using typeof to check if userInput is a string. If it is a string, print the uppercase version of the string to the console. If it's not a string, print "Not a string" to the console.

This demonstrates how unknown requires type checking before you can safely use type-specific methods like toUpperCase().

Cheat sheet

The unknown type can hold any value but requires type checking before performing operations:

let userInput: unknown = "Hello";
userInput = 42;        // No error
userInput = true;      // No error

Unlike any, TypeScript prevents operations on unknown values without type verification:

let data: unknown = "TypeScript";
// data.toUpperCase(); // Error! TypeScript doesn't know it's a string

// You must check the type first
if (typeof data === "string") {
    console.log(data.toUpperCase()); // Now it's safe!
}

This makes unknown safer than any by forcing type verification before using type-specific methods.

Try it yourself

// Create the userInput variable with unknown type
let userInput: unknown = "TypeScript";

// TODO: Write your code here
// Use typeof to check if userInput is a string
// If it's a string, print the uppercase version
// If it's not a string, print "Not a string"
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Introduction To TypeScript