TypeScript - Descriptive String Arrays

03/01/2021, Mon
Categories: #typescript

Strings from a Union Type

Often times, an array would contain one of many possible string values, and it would be expressed as such

interface BuildFlagsStatus {
  optionalArgsFlagKeys: Array<string>
}

However, this is a not very helpful approach because usually the string values allowed placement inside the array comes from a select group of strings.

To be more descriptive, create a string union type and use that for typing an array.

type optionalArgsFlagKeys = 'input' | 'output'
export type optionalArgsFlagKeysArray = optionalArgsFlagKeys[]

interface BuildFlagsStatus {
  optionalArgsFlagKeys: optionalArgsFlagKeysArray,
}

By importing the typed array, and using it directly on the array where the strings of the specified string values are defined, you will provide the TypeScript compiler enough clues to infer the proper value of the array.

import { optionalArgsFlagKeysArray } from './build-report';

export function buildFlags(this: Build, flags: Record<string, any>) {
  const acceptedRequiredFlagKeys = Build.requiredFlags,
    argsFlagKeys = Object.keys(flags),
    optionalArgsFlagKeys = intersection(Build.optionalFlags, argsFlagKeys) as optionalArgsFlagKeysArray;

  return {
    optionalArgsFlagKeys,
    argsFlagKeys
  };
}