Exclude invalid states at compile time
See original GitHub issueHello and thank you for your work. I wanted to ask what do you think about narrowing the type definition in such a way that compared entities would have to conform to a common interface in the first place?
- const equal: (a: any, b: any) => boolean;
+ const equal: <T>(a: T, b: T) => boolean;
We know that if they are not of the same runtime type, the comparison does not make sense. It would allow the consumers to exlude such cases at compile-time:
type Equal = <T>(a: T, b: T) => boolean;
const equal: Equal = (a, b) => a === b;
declare let someNumber: number;
equal(1, someNumber); // Makes sense
equal(1, ''); // Doesn't make sense
You can play with the idea in TypeScript playground.
Issue Analytics
- State:
- Created 5 years ago
- Comments:13 (7 by maintainers)
Top Results From Across the Web
Conditional compile-time inclusion/exclusion of code based ...
EDIT: here is a test case that shows what happens if you pass in the wrong number of template arguments: http://ideone.com/QzgNP.
Read more >Proposal: new "invalid" type to indicate custom invalid states
The idea is to make sure that there is a compile error any time an invalid type is inferred or otherwise pops up...
Read more >Warning Options (Using the GNU Compiler Collection (GCC))
This allows the use of new -Wno- options with old compilers, but if something goes wrong, the compiler warns that an unrecognized option...
Read more >C# preprocessor directives | Microsoft Learn
Learn the different C# preprocessor directives that control conditional compilation, warnings, nullable analysis, and more.
Read more >Compile-time Options - SQLite
This option adds extra logic to SQLite that inserts comment text into the output of EXPLAIN.
Read more >Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start FreeTop Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Top GitHub Comments
Just chiming in since I was mentioned – you want to think very carefully about the intent of this function. Consider this example:
TypeScript uses a special relationship called comparability when using something like the
===
operator to figure out if it’s “possibly true” that two types are comparable in a way that makes sense. There isn’t a way to re-use this relationship from “user code” (i.e. in a generic function) so it can make sense to use a looser signature (any
) to prevent false negatives.thanks, @RyanCavanaugh!
In light of that, my vote is stick with
(a: any, b: any) => boolean
for now. Especially considering that example with union types