DEV Community

Learning TypeScript

A. Sharif on February 12, 2020

I have written a 16 part "Notes on TypeScript" series, which is an unstructured collection of TypeScript related notes. Trying to convert this seri...
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

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.

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
 
zacharythomasstone profile image
Zachary Stone

I think having a solid grasp of what benefits Typescript gives and why you would use it over vanilla JS would be benefitial to beginners.

Collapse
 
busypeoples profile image
A. Sharif

Thanks for the feedback! Very good point regarding explaining the benefits of TypeScript.

Collapse
 
rizalrazuwan_98 profile image
rizal-razuwan

Just start my journey to TS...from python to Js with Ts...Thanks ya!

Collapse
 
lbayliss profile image
Luke Bayliss

Knowing when I'm looking at a good use for generics.

Collapse
 
busypeoples profile image
A. Sharif

Thanks for the feedback!