Re:Tricks I wish I knew when I learned TypeScript
by wdfx on Tuesday October 12, 2021 @01:50PM
(#28842758)
Your input parameter type should be unknown, not any.
Re:Tricks I wish I knew when I learned TypeScript
by Etheryte on Tuesday October 12, 2021 @01:56PM
(#28842838)
That's fairly subjective and I can see arguments for both sides, in the above example I've gone with the approach the Typescript documentation itself gives which uses any. Given the parameter is only used as an input, using any and unknown are interchangeable and there is no difference in this specific case.
Re:Tricks I wish I knew when I learned TypeScript
by wdfx on Tuesday October 12, 2021 @02:02PM
(#28842942)
I somewhat agree, but to me the semantics using unknown makes more sense as the function is attempting to answer a question of the input object.
"What is object? I don't know. Does it meet these conditions? Yes then object is Human else not."
Re:Tricks I wish I knew when I learned TypeScript
by Etheryte on Tuesday October 12, 2021 @02:45PM
(#28843471)
While I see where you're coming from, semantic formulation like this is highly subjective. All the same the problem statement could be "Given any kind of input, tell me whether it's a Human or not".
Re:Tricks I wish I knew when I learned TypeScript
by mikojan on Tuesday October 12, 2021 @03:20PM
(#28843896)
This approach is "correct" only when you're interacting with an API you have no control over whatsoever because specifying all this and maintaining it is really error prone.
All this boilerplate is not a proof. It remains an assertion. And so in most cases you might as well just add a "type"/"kind" property to your object (or create a class).
Re:Tricks I wish I knew when I learned TypeScript
by pbowyer on Tuesday October 12, 2021 @03:05PM
(#28843741)
> There are libraries which can automate this for you which is the route I would recommend
Which libraries do you recommend? I've had to do this a couple of times in my current project and it's painful (and I made mistakes).
Re:Tricks I wish I knew when I learned TypeScript
by Etheryte on Tuesday October 12, 2021 @06:09PM
(#28845660)
Personally I really enjoy Typanion [0] since it's very similar to Yup [1] which I previously had extensive experience with. You can find more alternatives and a lengthy discussion about the whole problem space and its history in [2].
[0] https://github.com/arcanis/typanion
[0] https://www.typescriptlang.org/docs/handbook/advanced-types....