useReadOnlySpread.js.flow 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. const meta = {
  2. messages: {
  3. readonlySpread:
  4. 'Flow type with spread property and all readonly properties must be '
  5. + 'wrapped in \'$ReadOnly<…>\' to prevent accidental loss of readonly-ness.',
  6. },
  7. };
  8. const create = (context) => ({
  9. TypeAlias(node) {
  10. if (node.right.type === 'GenericTypeAnnotation' && node.right.id.name === '$ReadOnly') {
  11. // it's already $ReadOnly<…>, nothing to do
  12. } else if (node.right.type === 'ObjectTypeAnnotation') {
  13. // let's iterate all props and if everything is readonly then throw
  14. let shouldThrow = false;
  15. let hasSpread = false;
  16. for (const property of node.right.properties) {
  17. if (property.type === 'ObjectTypeProperty') {
  18. if (property.variance && property.variance.kind === 'plus') {
  19. shouldThrow = true;
  20. } else {
  21. shouldThrow = false;
  22. break;
  23. }
  24. } else if (property.type === 'ObjectTypeSpreadProperty') {
  25. hasSpread = true;
  26. }
  27. }
  28. if (hasSpread === true && shouldThrow === true) {
  29. context.report({
  30. messageId: 'readonlySpread',
  31. node: node.right,
  32. });
  33. }
  34. }
  35. },
  36. });
  37. export default {
  38. create,
  39. meta,
  40. };