CodeBlanks Logo Icon CodeBlanks

Casting from unknown

Learn to safely cast from unknown.

The unknown type

unknown is the type-safe counterpart of any. You cannot use an unknown value directly; you must narrow it first. This is done with typeof or instanceof checks, or by asserting with as.

let hidden: unknown = "hi";
// hidden.toUpperCase();  error!
if (typeof hidden === "string") {
  console.log(hidden.toUpperCase());
}

Narrowing with typeof

The typeof operator checks primitive types. When you narrow an unknown value with a condition like typeof hidden === "string", TypeScript knows the value is string inside that block and allows string methods. This is the safest narrowing method.

Practice Narrow unknown to string

The gizli variable is of type unknown with value "merhaba". Check if it is string with typeof; if so, call toUpperCase() and print the result with console.log.

Starter code

index.ts
// gizli degiskeninin string olup olmadigini typeof ile kontrol et
// eger stringse toUpperCase metodunu cagir ve yazdir

const gizli: unknown = "merhaba";

Sample solution

index.ts
const gizli: unknown = "merhaba";
if (typeof gizli === "string") {
  console.log(gizli.toUpperCase());
}

Expected output

MERHABA

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What is needed to directly operate on an unknown variable?

  • Narrowing or asserting the type Correct answer
  • Copying the value to a new variable
  • Redeclaring it with const
  • Declaring the variable globally

Explanation: unknown values cannot be used directly; they must first be narrowed with typeof/instanceof or asserted with as.

2 The typeof operator

Question
const gizli: unknown = "selam";
if (____ gizli === "string") {
  console.log(gizli.toUpperCase());
}
Answer
const gizli: unknown = "selam";
if (typeof gizli === "string") {
  console.log(gizli.toUpperCase());
}

Explanation: The typeof operator checks primitive types; instanceof is for class instances.

3 unknown concepts

Term Meaning
unknown Type requiring narrowing
typeof Primitive type check
instanceof Class instance check
as Type assertion

All lessons in Intermediate