← All tasksTypeScript · Junior

Narrowing: formatValue

The function formatValue takes a string | number | Date | null | undefined and returns a string to show in a table.

A string comes back trimmed, a number with two decimals (3.14), a date as YYYY-MM-DD in UTC, and null or undefined as -. Keep the signature: inside the function TypeScript should know which type you are working with in every branch.

Tests (6)

Type tests are checked by the TypeScript compiler in strict mode. Expect<Equal<A, B>> passes when the types match exactly, and // @ts-expect-error passes when the next line does not compile. The first run downloads the compiler, so it takes a few seconds.

  1. types
    // @ts-expect-error - boolean is not allowed
    formatValue(true);
  2. types
    type _ = Expect<Equal<ReturnType<typeof formatValue>, string>>;
  3. expect(formatValue('  hello ')).toBe('hello');
  4. expect(formatValue(3.14159)).toBe('3.14');
    expect(formatValue(2)).toBe('2.00');
  5. expect(formatValue(new Date('2024-03-05T10:00:00Z'))).toBe('2024-03-05');
  6. expect(formatValue(null)).toBe('-');
    expect(formatValue(undefined)).toBe('-');