TypeScript: Typing Dynamic Objects and Subsets with Generics

How to use keyof, in, and extends keywords to type dynamic functions in TypeScript

Basic typing with primitive types

// article objectconst article = {
id: 1,
title: "TypeScript Explained",
active: true,
getSlug: () => 'typescript-explained',
};
// pick function, that returns an object with provided keysfunction pick (obj, keys): object {
throw "not yet implemented"
}
pick(article, ["title", "active"]);
{
title: "TypeScript Explained",
active: true
}

Restricting pick’s arguments with primitive types

function pick (obj: object, keys: string[]): object {
throw "not yet implemented"
}
Primitive type checks for the pick function.
// `content` property does not exist in `article`, but no error is displayedpick(article, ["title", "content"]);

Using keys and generics to limit object types

// pick with generic typefunction pick<T> (obj: T, keys: (keyof T)[]): object {
throw "not yet implemented"
}

keyof syntax

// some article type
type Article = {
title: string,
id: number,
...
}
// some key of article
type Key = keyof Article;
// some array of keys of article
type KeyArray = (keyof Article)[];
// string
type S1 = string;
// array of strings
type S1Array = string[];

Defining a generic return type

// pick with generic `object` return typefunction pick<T> (obj: T, keys: (keyof T)[]): object {
throw "not yet implemented"
}
// generic return type for `pick` that conforms to `obj` propertiestype Pick<T> = { [K in keyof T]: T[K] };function pick<T> (obj: T, keys: (keyof T)[]): Pick<T> {
throw "not yet implemented"
}

Typing the return type based on keys provided

// extract `title` from article via pick functionconst articleTitle = pick(article, ["title"]);type resolved = typeof articleTitle;
Entire article is expected — even if we only extract `title` from article object
type Pick<T, U extends keyof T> = { [K in U]: T[K] };function pick<T, U extends keyof T> (obj: T, keys: U[]): Pick<T, U> {
throw "not yet implemented"
}
Only the `title` property is now being returned by the function, as per the `keys` argument

In Summary

Programmer and Author. Director @ JKRBInvestments.com. Creator of LearnChineseGrammar.com for iOS.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store