TypeScript code: unknown Type > dev

Skip to content

Entire search within the site

👈Go back dev

TypeScript TypeScript code: unknown Type

page info

name Goposu datetime⏰ 25-10-10 15:27 hit👁️ 29 comment💬 0

text

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
👍good0 👎nogood 0

comment list 0

There are no registered comments.

이미지 목록

전체 19건 1 페이지
게시물 검색
Copyright © https://goposu.com All rights reserved.
View PC version