Susan Potter

TypeScript's keyof operator and possible uses

Sun October 10, 2020


In the last two weeks I learned about the keyof operator in TypeScript as I searched for a better solution to a problem we had in on of our internal client-side libraries at work.

Much of our TypeScript codebases at work use lodash although I am trying to encourage those developers to incorporate more ideas from fp-ts which provides ways of using common functional abstractions commonly found in Haskell and PureScript in TypeScript itself despite its lack of typeclass support.

Yet many of the frontend developers are more comfortable with lodash so we common have code that looks like this:

// definitions
type Portfolio = {
  id: integer,
  name: string,
  investments: Array<Investment>,

type Investment = {
  identifier: string,
  investmentType: InvestmentType,

type InvestmentType = 'CommonStock' | 'CorporateBond';

// Mock data for usage examples:
const investement: Investment = { identifer: "ABC", investmentType: 'CommonStock', vendorSymbols: [] };
const getPortfolioById = (id: number): Portfolio => ({ id: id, name: 'Demo', investments: [investment] });

// usage code example
const portfolio: Portfolio = getPortfolioById(1234);
const firstInvestmentId: string = _.get(portfolio, 'investments[0].identifier');
const firstInvestmentType: InvestmentType = _get.get(portfolio, 'investment[0].investementType');

Wouldn't it …