My TypeScript cheat-sheet

Photo by Web Donut on Unsplash
Refill!

TypeScript became essential part of my professional activity. It got to the point that if I see pure JavaScript code, I simply can't acknowledge that. I immediately start asking myself "How is that possible for a language to not to have types?".

So in this article I will keep collecting all the tricks I have learned so far, as well as any cool projects I managed to find on the TypeScript topic.

Extend one complex type from another

I am not a huge fan of interfaces and inheritance, since there is plenty of ways to create a derivative type, via "union" and a few extra tricks:

type CarType = {
speed: number;
color: string;
model: string;
};
// Add a subset of properties from CarType
type PlaneTypeA = {
class: string
} & Pick<CarType, 'speed' | 'model'>;
// Add one property from CarType
type PlaneType = {
class: string;
speed: CarType["speed"];
};
// "Inherit" type
type SuperCarType = {
super: boolean;
} & CarType;

Typing static class methods

Not a huge sucker for OOP either, but occasionally I have to deal with it. So,

interface CommandProcessorInstance {}
export interface CommandProcessor {
new (): CommandProcessorInstance;
attach(program: CommanderCommand): void;
process(args?: CommandActionArguments): Promise<void>;
}
export function Implements<T>() {
return <U extends T>(constructor: U) => {
// eslint-disable-next-line no-unused-expressions
constructor;
};
}
@Implements<CommandProcessor>()
export class CommandRun {
public static attach(
program: CommanderCommand,
) {
// ...
}
public static async process(
args: CommandActionArguments,
) {
// ...
}
}

Typeof

Sometimes I can't import types from a third-party library, or I simply don't have types explicitly defined. Nevertheless, there is a way to declare a variable to be of the same type as the other variable:

const data = [
{ name: 'Alex', position: 'pilot' },
{ name: 'Amos', position: 'tech' },
];
const crewMember: typeof data[0] | undefined;

Indexed vs Mapped Object

type MyMappedObjectType = {
[k in string | number]: string;
};
type MyIndexedType = {
[k: string]: string;
};

No rest for an engineer, so, yeh, to be continued...

Sergei Gannochenko

Business-oriented fullstack engineer, in ❤️ with Tech.
JS / JS stack: React, Node, Docker, AWS.
15+ years in dev.