← 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.
Ctrl+Enter runs the tests. Tab indents; to leave the editor with the keyboard, press Esc and then Tab. Your code is saved in this browser.
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.
- types
// @ts-expect-error - boolean is not allowed formatValue(true);
- types
type _ = Expect<Equal<ReturnType<typeof formatValue>, string>>;
expect(formatValue(' hello ')).toBe('hello');
expect(formatValue(3.14159)).toBe('3.14'); expect(formatValue(2)).toBe('2.00');
expect(formatValue(new Date('2024-03-05T10:00:00Z'))).toBe('2024-03-05');
expect(formatValue(null)).toBe('-'); expect(formatValue(undefined)).toBe('-');