I’m working in a legacy code base with JS files, not TS. However I’m adding tsc to validate types.
one way that TS inferring types for arguments is based on default value. So a function like
function doSomething(withProp = 5) {
...
}
withProp
is presumed to always be a number, so trying to call parseInt(withProp)
would not be happy.
I know I can use JSDocs to correct types, but in this case I’m dealing with an anonymous function deep inside a getter tree for Vuex. Is there another way to provide types for these args?
2
Answers
withProp = 5
in your code reflects thedefault
value ofarg
, but it doesn’t mean to be always a numbertype
ofarg
.If you pass any
string
orobject
as an argument, its type might be changed according to the incoming argument.The best way checking your type is to create an utility function which detects the type of your argument. ( you can use If … else if.. else )
And then you can invoke this function inside of getter for validating the incoming argument.
Certainly! Let’s format the code correctly. Here are some ways to handle type inference for function arguments with default values in JavaScript:
Using Default Parameters (ES6/ES2015):
withProp
is a number based on the default value.JSDoc Type Annotations:
Explicitly Cast Default Value:
withProp
is always a number, explicitly cast the default value:Type Assertion Inside the Function:
parseInt(withProp)
within the function, use type assertions:Function Overloads:
withProp
is provided or not.Remember to choose the approach that best fits your specific use case and maintainability requirements. 😊
Source: Conversation with Bing, 2023/11/13
(1) Set a default parameter value for a JavaScript function. Set a default parameter value for a JavaScript function.
(2) How to Set Default Parameter Value for a JavaScript Function. https://www.tutorialrepublic.com/faq/how-to-set-default-parameter-value-for-a-javascript-function.php.
(3) How to set default function arguments with vanilla JS. https://gomakethings.com/how-to-set-default-function-arguments-with-vanilla-js/.
(4) JS: functions arguments default values – Stack Overflow. JS: functions arguments default values.
(5) How To Set Default Parameter Values for JavaScript Functions – W3Schools. https://www.w3schools.com/howto/howto_js_default_parameters.asp.