Hacker News new | ask | show | jobs
by phailhaus 1399 days ago

    declare function addClass(...classes: (string | string[] | (() => string))[]): void;
It's pretty straightforward in Typescript. And when you go to implement it, tsc will make sure you cover all the types your function claims to support.

> This is very useful to create a library like jquery that you can initialize straight away without needing (but also being able to use) the `new` keyword, just calling it like a function and always ensures it returns an instance.

Avoiding having to type "new" is not a very compelling reason to avoid Typescript, especially because Typescript won't let you make the mistake of calling the function without it. It's just not a problem.

1 comments

That's an order of magnitude less clear in what the function expects than the examples I gave IMHO
Actually, it's not. With the type signature I understand what arguments the function can take. With your examples I have to _infer_ that, and there could be other restrictions that I wouldn't know. Like, can you pass a function and a string? Or do all the arguments have to be functions or not? The type signature tells me right away.
How are literal examples that are strings less clear than saying "string"? How do you know with just "string" the separator method, the format, etc? In my example you have type information AND string format information AND examples, while with TS you'd only have type information
Again, TS does not forbid you from having examples. Your docstrings don't replace Typescript, and Typescript doesn't replace good docstrings. But your docstrings are very unclear on which types you can mix together, and that has to be inferred. And if a user passes in something else by accident, it will fail at runtime rather than warning them the moment they write it.
Who's stopping you from giving examples in a docstring?
You can use recursion and template types to type some pretty complex string values now - I've seen cut down parsers for both SQL and TS written just via TS types which is madness but does show what can be done.

Whether the effort is worth it is, however, a totally different question to whether it's possible.