简体   繁体   中英

Set default value of property of object passed on parameter to function

The key difference on this question is I want to keep my property referenced inside the object, not destructured.

export interface MapSettings {
  up: 'trueNorth' | 'runIn' | 'magneticNorth' | 'user';
  rotation?: number;
}

type MapProps = {
  settings: MapSettings;
};

export const Map: FunctionComponent<MapProps> = function Map({
  settings,
}) {

I want to set a default value for settings.rotation but I also want to keep it referenced as settings.rotation because settings has a lot more properties than shown here and I know where the value is coming from.

This is the best answer I can come up with:

export const Map: FunctionComponent<MapProps> = function Map({
  settings: { rotation: settingsRotation = 360, ...settings },
}) {

But it doesn't let me reference settings.rotation with a default value of 360 .

just check it and set it:

export const Map: FunctionComponent<MapProps> = function Map({
  settings,
}) {
  settings.rotation = (settings.rotation || settings.roation === 0) ? settings.rotation : 360

Default value is mentioned as { someKey = 'defaultValue' } insead of `{ someKey: 'defaultValue' }

So you can write it like

{
   settings = { rotation: settingsRotation = 360 },
}

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