पाठ 24 / 28

keyof, typeof और Type Assertions

keyof और typeof से values व keys से types निकालें, और type assertions केवल तब उपयोग करें जब वे उचित हों।

keyof किसी object type की keys का union बनाता है; typeof किसी मौजूदा value का type पढ़ता है।

const user = { id: 1, name: "Ada" };

type User = typeof user;       // { id: number; name: string }
type UserKey = keyof User;     // "id" | "name"

function getProp<T, K extends keyof T>(obj: T, key: K): T[K] {
  return obj[key];
}
getProp(user, "name");   // string
getProp(user, "age");
// Error: Argument of type '"age"' is not assignable to parameter of type '"id" | "name"'.

Type assertion (as) compiler को बताता है कि आप उससे ज़्यादा जानते हैं। यह runtime पर value नहीं बदलता।

const el = document.getElementById("email") as HTMLInputElement;
el.value = "a@x.com";

const n = "5" as number;
// Error: Conversion of type 'string' to type 'number' may be a mistake.

as की जगह type guard से narrowing को प्राथमिकता दें। as केवल तब उपयोग करें जब आपके पास ऐसी जानकारी हो जो compiler नहीं देख सकता, और ऐसी error दबाने के लिए कभी नहीं जिसे आप समझते नहीं।