简体   繁体   中英

Set the default value for the key of the function object parameter

I need to transfer some 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've tried to do it in this way, but it hasn't worked ) { /*function body*/ } 

You can see that secureTextEntry is an optional parameter. So, I want to define some default value for this prop. How can I do this?

You will have to do it while destructuring unfortunately, (or fortuntately?)

 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

To address your concern of the default value being after the rest of the props, it is not an issue with typescript set to target es5 as the rest syntax gets transpiled away into something like below,

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

    /* code to handle rest omitted */

    console.log(secureTextEntry); 
}

As you see, with the above transformation the order of the spread does not matter and my code snippet behaves correctly as a result. However, since it makes no logical sense to capture the "rest" of the keys before the others, the ES2018 standard and Typescript require you to place it behind the destructured keys { secureTextEntry = false, ...rest } .

(I missed this the first time because I copy edited your code and it ran fine since the typescript compiler on this site is set to emit even if it detects "compile errors" and since I wasn't actually using ...props inside the function, I didn't realise that the rest parameter transformation wasn't working properly. You should see the transpilation in action yourself.)

I wouldn't use destructuring at all, rather put the optional property on a new object:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM