DEV Community

Discussion on: 150+ Typescript one-liners [code snippets].

Collapse
 
joelbonetr profile image
JoelBonetR 🥇 • Edited

Hi Christian,

As advice, take care when using TS. It sets you in a peace of mind state, thinking that you'll be available to set only the types you defined for each property but that's not how it works.

If you set

export const isEmpty = <T, \_>(arr: T[]): boolean => Array.isArray(arr) && !arr.length;
Enter fullscreen mode Exit fullscreen mode

in a package, lib or js SDK, other software will still be capable of sending 'non expected' data into it and it's not protected or workarounded to ensure the reliability:

The transpiled to JS version will look like that:

export const isEmpty = (arr) => Array.isArray(arr) && !arr.length;
Enter fullscreen mode Exit fullscreen mode

in which case:

isEmpty();  // false
isEmpty('') // false
isEmpty(null) // false
isEmpty(undefined) // false
Enter fullscreen mode Exit fullscreen mode

The reason is that Array.isArray(arr) evaluates into false thus returning false directly and the short circuit AND operator is not evaluated.

Some cases like that leads you to avoid one-liners for good:

const isEmpty = (arr) => {
    if(Array.isArray(arr)) return !arr.length 
    else throw `isEmpty error, Array expected but found ${typeof arr}`;
}
Enter fullscreen mode Exit fullscreen mode

Now you can translate that into TS if you want but it just doesn't matter, either it beign JS or TS, it will be reliable and not depend on the target devs to use TS as well (which of course still won't cover API responses and so unless you specificaly typecheck them etc...).

Cheers!