ADVERTISEMENT
Google AdSense Slot (headerLeaderboard)

Set your Publisher ID in src/config/ads.ts to display live ads.

TypeScript Tutorial• 7 min read

Primitive Types, Arrays & Tuples

Mastering string, number, boolean, any, unknown, and fixed-length arrays

TypeScript provides type annotations for JavaScript primitives, along with powerful specialized types like unknown, never, and fixed-size tuples.

Type Taxonomy: Any vs Unknown

string, number, boolean: Standard primitives.

any: Disables type checking entirely. Avoid using any whenever possible as it defeats the purpose of TypeScript.

unknown: The type-safe counterpart of any. You cannot perform operations on an unknown value without first narrowing its type via typeof or type guards.

never: Represents values that never occur, such as a function that always throws an error or an impossible conditional branch.

Tuples: Fixed-length arrays where each position has a specific predetermined type: [string, number].

Working with Tuples and Unknown Types
// Fixed-length coordinate tuple: [Latitude, Longitude]
const coordinates: [number, number] = [37.7749, -122.4194];

// Safe handling of untrusted third-party API response
function processApiResponse(payload: unknown): string {
  // Type narrowing check
  if (typeof payload === 'string') {
    return payload.toUpperCase();
  }
  if (typeof payload === 'object' && payload !== null && 'message' in payload) {
    return String((payload as { message: unknown }).message);
  }
  return 'Unknown payload structure';
}

console.log(processApiResponse({ message: "System online" }));
unknown forces developers to verify types before accessing properties or invoking methods.
ADVERTISEMENT
Google AdSense Slot (inContentBanner)

Set your Publisher ID in src/config/ads.ts to display live ads.

Test Yourself With Exercise

+15 XP

Why is "unknown" preferred over "any" when receiving unverified external data?