TypeScript’s type system is gradual: when describing a JavaScript value with TypeScript, you can be more or less accurate, ranging from saying that the value could be anything (any), to describing in absolute detail what the value is under different conditions. Consider for example this function which prints the property of an object - if it exists: function printProperty(obj, key) { if (typeof obj === "object" && obj !== null && Object.hasOwn(obj, key)) { console.log(obj[key]); } } We can type it in a loose way as follows: function printProperty(obj: any, key: string) { if (typeof obj === "object" && obj !== null && Object.hasOwn(obj, key)) { console.log(obj[key]); } } But we can also be more strict, requiring obj to be an object and key to be one of its properties: function printProperty<Obj extends object>(obj: Obj, key: keyof Obj) { console.log(obj[key]); } The strictness even allows us to remove the if check inside the function, since now TypeScript gives us the compile-time guarantee that obj will always have property key: // Passing in a non-existing property gives an error. printProperty({ a: "a" }, "b");Argument of type '"b"' is not assignable to parameter of type '"a"'. Having this additional guarantee is obviously desirable, but it comes at the expense of making the type definition more complex. Not much in this case - the type is still very understandable - but it reveals an inherent trade-off. Where should we draw the line? Lately I’ve been trying out a few libraries that - in pursuit of perfect type safety - make their typings so complex that it makes them almost unusable, in my opinion. I call this approach hyper-typing, and I worry it’s becoming a trend in the TypeScript ecosystem. I get why, actually. I myself am often a hyper-typer! It’s a slippery slope: “If I add this type constraint then the caller will get an error in this particular case”. “I can make this function infer this type here so the caller will get the correct type hint there”. At th...
First seen: 2025-05-08 08:20
Last seen: 2025-05-19 10:54