admin管理员组

文章数量:1418410

Is it possible to define a type for an object's with a required key value pair and a default key value pair?

Example:

const myComponent = (props) => {
  const {
    myObject: {
      someRequiredString,
      someNotRequiredString,
    }
  }
}

myComponent.propTypes = {
  myObject: PropTypes.shape({
    someRequiredString.string.isRequired,
  }).isRequired,
}

myComponent.defaultProps = {
  myObject: {
    someNotRequiredString: '',
  }
}

Is it possible to define a type for an object's with a required key value pair and a default key value pair?

Example:

const myComponent = (props) => {
  const {
    myObject: {
      someRequiredString,
      someNotRequiredString,
    }
  }
}

myComponent.propTypes = {
  myObject: PropTypes.shape({
    someRequiredString.string.isRequired,
  }).isRequired,
}

myComponent.defaultProps = {
  myObject: {
    someNotRequiredString: '',
  }
}
Share Improve this question asked Aug 13, 2019 at 11:32 RemiRemi 5,36713 gold badges60 silver badges94 bronze badges 2
  • 1 Usually required field didn't have a default value – Vadim Hulevich Commented Aug 13, 2019 at 11:37
  • True, but how about an object which has both a required and not required field? @VadimHulevich – Remi Commented Aug 13, 2019 at 12:47
Add a ment  | 

2 Answers 2

Reset to default 4

So if i understand you correct, you need non-required object bit if this object exist it's must have 2 required field, and maybe one non-required

So here we are:

ponentForUser.propTypes = {
    myObject: PropTypes.shape({
        name:PropTypes.string.isRequired,
        secondName:PropTypes.string.isRequired,
        age:PropTypes.string,
    }),
}

ponentForUser.defaultProps = {
    myObject: {
        name: 'defaultName',
        secondName: 'defaultSecondName',
        age:21
    }
}

In this case if User object is not required, instead of this you will get User with properties:

myObject: { name: 'defaultName', secondName: 'defaultSecondName', age:21 }

But if from props you will get object User without name, you catch Warning about required name and secondName.

Maybe this has changed since this question was asked, but you can't provide defaultProps for a nested value like this.

本文标签: javascriptCan a default value be used in a proptype shapeStack Overflow