Lesson 24 / 28
keyof, typeof & Type Assertions
Derive types from values and keys with keyof and typeof, and use type assertions only when they are justified.
keyof produces a union of an object type's keys; typeof reads the type of an existing value.
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"'.A type assertion (as) tells the compiler you know more than it does. It does not change the value at runtime.
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.Prefer narrowing with a type guard over as. Use as only when you have information the compiler cannot see, and never to silence an error you do not understand.