TypeScript code: unknown Type > dev

Skip to content
Entire search within the site

dev

TypeScript TypeScript code: unknown Type

page info

profile_image
Author Goposu
comment 0co View 27hit Creation date 25-10-10 15:27

๋ณธ๋ฌธ

TypeScript code: unknown Type

TypeScript unknown Type

The unknown type in TypeScript is used when you want to accept any value, but require type checking before using it. It is safer than any because TypeScript forces you to verify the type before performing operations.

Basic Usage

let value: unknown;

value = "hello";   // OK
value = 42;        // OK
value = true;      // OK

Unsafe Access

let value: unknown = "hello";
console.log(value.toUpperCase()); // Error: Object is of type 'unknown'

Safe Access with Type Checking

if (typeof value === "string") {
  console.log(value.toUpperCase()); // OK
}

Type Assertion

console.log((value as string).toUpperCase()); // OK

Comparison: unknown vs any

Type Description
any Allows any value and any operation without checks (unsafe)
unknown Allows any value but requires type checking before use (safe)

When to Use unknown

  • Handling external data (e.g., API responses)
  • Processing user input
  • As a safer alternative to any
์ถ”์ฒœ0 ๋น„์ถ”์ฒœ0

comment list

There are no registered comments.

Total 19๊ฑด 1 page

search

memberlogin

join

Copyright © https://goposu.com All rights reserved.