re: Learning TypeScript VIEW POST

re: I am forever bugged by function objGet<T> (a: Record<string, T>, k: string): T { return a[k] } function arrayGet<T> (a: T[],...

Here is a solution for the problem with objGet:

function objGet<T, K extends keyof T>(o: T, k: K) {
    return o[k];

const a = [1, "Test", { id: 1, name: "test" }];

const User = {
    id: 1,
    name: "Test User",
    points: 20

const id = objGet(User, "id"); // number
const points = objGet(User, "points"); // number
const userName = objGet(User, "name"); // string
// const somethingElse = objGet(User, "nonExistent");
// !Error
// Argument of type '"nonExistent"' is not assignable to parameter of type '"id" | "name" | "points"'.

We can limit the possible lookup keys by using keyof T, which would prevent calling any undefined keys. This would also ensure that the correct type is written for any provided lookup key.

Code of Conduct Report abuse