DEV Community

Discussion on: Learning TypeScript

Collapse
 
busypeoples profile image
A. Sharif

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.