Establish the primary value for the key within the parameter of the function object

I'm facing the challenge of transferring certain props into my component.

type Props = {
  icon: number,
  onChangeText: Function,
  onEndEditing: Function,
  placeholder: string,
  secureTextEntry?: boolean
};
export default function LRInput(
  props: Props = { ...props, secureTextEntry: false } // I attempted this approach but it didn't work 
) { /*function body*/ }

As you can see, secureTextEntry is an optional parameter. How can I set a default value for this prop?

Answer №1

Instead of employing destructuring, my preference would be to assign the optional property to a fresh object:

export default function LRInput(props: Props) {
     const defaultedProps: Props = { secureTextEntry: false, ...props };
    /* code within the function */
}

Answer №2

It is necessary to handle destructuring while performing this task, whether it be seen as unfortunate or fortunate.

type Props = {
  icon: number,
  onChangeText: Function,
  onEndEditing: Function,
  placeholder: string,
  secureTextEntry?: boolean
};
function LRInput(
  { secureTextEntry = false, ...props }: Props
) { console.log(secureTextEntry) }

LRInput({ icon: 5 })
LRInput({ icon: 5, secureTextEntry: true })

Edit

In response to your concern about the default value appearing after the rest of the props, when targeting es5 in typescript, there should not be an issue because the rest syntax is transpiled accordingly as shown below,

function LRInput(_a) { 
    var _b = _a.secureTextEntry;
    var secureTextEntry = _b === void 0 ? false : _b; 

    /* code to handle rest omitted */

    console.log(secureTextEntry); 
}

It is evident that with this transformation, the order of spread does not affect functionality. However, for logical coherence, ES2018 standard and Typescript dictate placing the "rest" parameter after the destructured keys

{ secureTextEntry = false, ...rest }
.

(My oversight initially occurred due to editing the code which executed without error on this site's typescript compiler set to emit despite detecting errors. Since I did not utilize ...props within the function, the issue with rest parameter transformation went unnoticed. You can witness the transpilation process here for yourself.)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

load a particular section of another website into my own div

Similar Question: Ways to bypass the same-origin policy I've been looking for a way to load a specific div from another website using this code. Can anyone provide an example of how to do this on jsfiddle? $.ajax({ url: 'http://somethin ...

Is there a way to retrieve and store a JSON object from a URL using JavaScript and jQuery?

I have a PHP page that is returning a JSON object in the correct format, like this: [ { "name":"Users", "parent":"null", "children":[ { "name": "adsd", "parent": "Users", "children": [] } , { "name": "ca", "p ...

Retrieving information from MongoDB queries using Node.js

I am facing an issue while trying to retrieve data from the find() method and use it outside the method. My goal is to incorporate this data into a JSON response. Unfortunately, my current code is not working as expected and the data is not accessible outs ...

What could be causing the NextJS query string to be undefined upon reloading the page?

I am currently working on a NextJS application where I have created a search results page that relies on a query parameter being passed. To grab the query string, I am using the next/router package. The issue I am facing is that after the initial load of t ...

The React apexchart heatmap's height remains static despite attempting to change it through state updates

Seeking to dynamically resize the height of an "Apexcharts heatmap" based on server data. Despite attempting to manipulate code in various lifecycle methods, including componentDidMount() and where the data is received, I have not been successful. Within ...

Make sure that the parent element is only visible once all of its child elements have

As a newcomer to the world of react, I am facing some challenges. I have created a form in react which includes a dropdown. To ensure reusability across multiple pages, I decided to turn this dropdown into a component that is responsible for fetching all n ...

Child component being used within a parent component in VueJS

Currently, I am in the process of transforming an existing theme into reusable components. One of the components I have created is a button component structured as follows: <template> <a :href="link" class="button" :class="styling"><sl ...

What is the importance of having the http module installed for our Node.js application to function properly?

After exploring numerous sources, I stumbled upon this code snippet in the first application: var http = require('http'); http.createServer(function (req, res) { res.writeHead(200, {'Content-Type': 'text/plain'}); r ...

Exploring the basics of caching in Node.js and Express: a beginner's

Picture an application with numerous users and small sets of data (up to 10 name/value pairs), but the process to access this data involves complex calculations. The concept is based on a system with a 'history' state that is crucial for obtaini ...

Fill in the form using JSON data by matching the names with their corresponding values

Here is how I am collecting and storing the data from my web form as JSON, utilizing the name attribute and values. What is the best way to populate the form again with the saved JSON data in the same structure using name and value? (context: I will keep ...

Is it possible for SqlCommand.ExecuteReader to automatically open the database connection?

Unusual behavior is happening on my website. I have a WCF Data service that provides JSON data to populate a jqGrid using javascript/ajax calls. In addition, there is server-side code that also accesses the same WCF service to retrieve data. Within my WC ...

"Running experiments with Google Ads and Google Analytics scripts results in a blank page being displayed

Currently, I am working on a plain HTML file and conducting tests to ensure that the Google Ads and Analytics scripts are functioning correctly before implementing them on other pages. A colleague who has an AdSense account provided me with the script code ...

Ways to identify the current configuration of ckeditor in use

I've created a custom CKEditor plugin with a unique dialog box setup. To include the dialog, I use the following code: var customize_dialog = this.path + 'dialogs/customdialog.js' ; CKEDITOR.dialog.add( myPluginName, customize_dialo ...

How is it possible that the fourth element in the array displays a length of 24 when all it contains is the word "Spain"?

One challenge I'm facing is comparing the 5th element of my array with the value of the object that has been clicked. Below is the code snippet I am currently using: var options = new Array(); $(".option").click(function compareReaction(name) { ...

Pictures are not showing up in the gallery after they have been saved

if (action.equals("saveToGallery")) { JSONObject obj = args.getJSONObject(0); String imageSource = obj.has("imageSrc") ? obj.getString("imageSrc") : null; String imageName = obj.has(" ...

In the Sandbox, element.firstChild functions properly, but it does not work in the IDE

Encountered an issue that has me puzzled. To give you some context, I attempted to create a native draggable slider using React and positioned it in the center of the screen, specifically within my Codesandbox file. The code snippet I utilized is as follow ...

jquery survey quiz

Currently, I am attempting to develop a jQuery questionnaire, but my limited knowledge in the area is proving to be quite inadequate. So far, here is what I have: Upon clicking on "Questions," a pop-up window will appear with two questions. My goal is t ...

Error: The bun.js application encountered a SegmentationFault at line 188

I'm attempting to execute the following command on my current repository, which already has a registry set up in the .npmrc. bun install -y The purpose of the -y flag is to generate the yarn v1 lockfile. However, it's resulting in the followin ...

What is the process for removing an element from my Reducer Object?

I'm facing a challenge with my reducer object structure. Here's an example of what it looks like: clientData : { 1080 : [{ID : 1111,name : 'John'},{ID : 2222,name : 'Stan'},], 1090 : [{ID : 3333,name : 'Adam'},{ ...

Having issues setting a property value on a Mongoose result in a Node.js application

Hello there, I am currently working with a MongoDB object retrieved via a findById method, and I need to convert the _id within this object from an ObjectID type to a string. I have developed the following function: student: async (parent, { _id }, ...