#Proper way to check/validate type

1 messages · Page 1 of 1 (latest)

lusty pendant
#

i have a simple function:

    /**
     * @param {string} [pathname] - pathname of the element
     * @return {string}
     */
    function PathToUserID(pathname: string): string | null
    {
        if (pathname && pathname.length > 30)
        {
            const split = pathname.split('/');
            if (split.length >= 3 && split[2].length >= 32)
                return split[2].trim() ?? null;
        }
        return null;
    }

What is the accepted/best practices way to validate the received parameter is typeof string without much sacrifice of the performance? I know I can use (typeof x === 'string') but as usual, there is always a Stackoverflow post with 3534546456674874 upvotes saying how it is actually bad idea and all these check add up and and accumulate perf. penalty and such.
Just wanted some more insight into this.

ornate plover
#

why would you want to check this when using a typed language?

lusty pendant
#

Because it is compiled down to javascript in the end and anything can go in and out in JS

#

You arent suggesting to check it at call-site? Because it is called in a lot of places and that means repeating the same code quite a lot of times where as I could just put it inside single function. it isn even DRY memes it is common sense