Recommended behavior for JavaScript functions when a parameter is not of the expected type

Viewed 22

I'm planning to release open source some of the code I've written in the last years as packages in hope they can be useful for someone or someone else maybe improve them.

In this process I want to conform to the recommended guidelines / best practices / standards adopted by the JavaScript community as of 2022.

Given a function / method that expects as parameter a string (for example) I see two ways to deal with parameters of a different type:

// 1 - permissive: cast to correct type whenever possible

function f( str )
{
    if( typeof str === 'undefined' ) str = ''; // accepting also nothing passed
    else if( typeof str === 'number' || typeof( str ) === 'boolean' ) str = '' + str;
    else if( typeof str !== 'string' ) throw new TypeError();

    // ...
}


// 2 - strict: accept only the expected type, throw exception otherwise

function f( str )
{
   if( typeof str !== 'string' ) throw new TypeError();
   
   // ...
}

I prefer nr. 2 because I see more risks than advantages in the nr. 1 "tolerant" approach.

Anyway the question is: is there a widely accepted recommended best practice or it is still up to the library's developer preference / style ?

0 Answers
Related