DEV Community

Discussion on: Learning TypeScript

Collapse
 
patarapolw profile image
Pacharapol Withayasakpunt • Edited

I am forever bugged by

function objGet<T> (a: Record<string, T>, k: string): T {
  return a[k]
}

function arrayGet<T> (a: T[], n: number): T {
  return a[n]
}

Why not T | undefined? What is a good way to override this behavior.

Also, I am looking for a good series on Vue TypeScript. Recently I got this behavior solved, $mq.

Mostly the problem is always, extending incomplete typed libraries, or JSDoc is lost, and VSCode showing the useless, declare module '...' instead. (No, they are not telling how to properly write declaration.d.ts or even src/@types/.../index.d.ts. They don't even provide a link, only No quick fixes available.).

The other way round is problematic too. I cannot write JSDoc @type from TypeScript types / interfaces.

Collapse
 
busypeoples profile image
A. Sharif

Thanks for the great example and feedback! Don't know too much about Vue, but will definitely have a look at the example you posted.

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.