Skip to content

[Bug]: react/prefer-read-only-props for Typescript #3535

Closed
@thany

Description

@thany

Is there an existing issue for this?

  • I have searched the existing issues and my issue is unique
  • My issue appears in the command-line and not only in the text editor

Description Overview

When I add react/prefer-read-only-props it doesn't detect read/write props defined using Typescript. The documentation suggests only towards the detection of types defined in Flow, so it makes sense (to me) that this rule can perform the same detection for Typescript as well.

Example of incorrect code:

interface ImageProps {
  src: string;
  alt?: string;
  width?: number;
  height?: number;
}

const Image: React.FC<ImageProps> = ({ src, alt, width, height }) => (
  <img src={src} alt={alt ?? ''} width={width} height={height} />
);

Examples of correct code:

interface ImageProps {
  readonly src: string;
  readonly alt?: string;
  readonly width?: number;
  readonly height?: number;
}

const Image: React.FC<ImageProps> = ({ src, alt, width, height }) => (
  <img src={src} alt={alt ?? ''} width={width} height={height} />
);
type ImageProps = ReadOnly<{
  src: string;
  alt?: string;
  width?: number;
  height?: number;
}>;

const Image: React.FC<ImageProps> = ({ src, alt, width, height }) => (
  <img src={src} alt={alt ?? ''} width={width} height={height} />
);
interface ImageProps {
  src: string;
  alt?: string;
  width?: number;
  height?: number;
}

const Image: React.FC<ReadOnly<ImageProps>> = ({ src, alt, width, height }) => (
  <img src={src} alt={alt ?? ''} width={width} height={height} />
);

I'm not sure what to do about advanced usage, so when pulling extra interfaces from other files, and unioning them into the ImageProps interface.

Expected Behavior

This rule should not only check Flow, but also Typescript.

Perhaps also a good idea to enforce how readonlyness is achieved (readonly keyword, ReadOnly<T> type, or React.FC<ReadOnly<T>> component, or something else?)

eslint-plugin-react version

7.32.2

eslint version

8.34.0

node version

18.13.0

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions