TypeScript Template Literal Types Can Catch Object Path Typos at Compile Time
A common pattern passes dot-separated property paths as plain strings, so a misspelled key like "colros" compiles without error and fails only at runtime. The typical fix of using keyof only checks one level deep, which is insufficient for nested paths. The article shows how template literal types combined with recursive conditional mapped types can generate a union of every valid dot-path from an object's declared shape. Because the union is derived from the type itself rather than written by hand, typos are rejected by the compiler. The approach requires only about fifteen lines of code and relies on a feature available since TypeScript 4.1.
This is an AI-generated summary. ShortSingh links to the original source for the complete article.
Discussion (0)
Log in to join the discussion and vote.
Log in