Should we return undefined or null? #47
Replies: 5 comments 3 replies
-
Would we ever run into this scenario where we can identify a provider, but not find a url? So the return object might look like:
If cases like this are found quite a bit, then of course, an issue or PR should be opened, if there is an actual |
Beta Was this translation helpful? Give feedback.
-
Did it ever happen? Because id's at least on youtube are pretty standard and will always be found. Also, I'm happy with an empty object instead of undefined, because of the reasons you mentioned. |
Beta Was this translation helpful? Give feedback.
-
Some more thoughts on this came up recently in this PR: #52 |
Beta Was this translation helpful? Give feedback.
-
Hi @radiovisual, I didn't know about this discussion. I'll add my thoughts after what you said in #52. You make good points. Then probably the easiest way forward to have usable type definitions is this: export default function getVideoId(
url: string
): {
id: string | null;
service: "youtube" | "vimeo" | "vine" | "videopress" | null;
}; This can encode all potential scenarios:
However this types would allow for an impossible case where the export default function getVideoId(
url: string
): {
id: string | null;
service: "youtube" | "vimeo" | "vine" | "videopress";
} | null; In this case, when the returned value is not I am happy to update my pull request to reflect the case you decide to go for. Thanks a lot! |
Beta Was this translation helpful? Give feedback.
-
@4lejandrito My vote would be for the types to look like this: export default function getVideoId(
url: string
): {
id: string | null;
service: "youtube" | "vimeo" | "vine" | "videopress" | null;
}; I am OK with the fact that these type definitions support the impossible case where an I also really want to avoid returning null or undefined in the case that neither an const fn1 = () => undefined;
const { id, service } = fn1();
// TypeError: Cannot destructure property 'id' of 'fn1(...)' as it is undefined.
const fn2 = () => ({});
const { id, service } = fn2();
// id => undefined, service => undefined If anyone ever encounters this impossible case where an id is found but a service is not, then hopefully they open a PR or report the bug. 😄 |
Beta Was this translation helpful? Give feedback.
-
Back when I first created this module, I used to just return an
id
String or undefined when an id was not found. Then, the request came in that the module returns theservice
provider as well, which made a lot of sense, so then there came a major version bump and the return values of an object like this:When an
id
is found:This lets us do easy destructuring like this:
But what happens if no id is found?
When no
id
is foundThen we return an empty object
{}
, which can still be friendly to destructuring:What are your thoughts between undefined and and an empty object?
Beta Was this translation helpful? Give feedback.
All reactions