Home > OS >  Make React Props Readonly in Typescript
Make React Props Readonly in Typescript

Time:12-04

I heard that React Props is read only by default, however, I could overwrite props value in a component without errors. Is there settings to make props read only?

interface Props {
  readonly isText: boolean;
}

const ComponentA: FC<Props> = ({isText}: Props) {
  isText = false // <- I can change isText even if I add readonly. why?

  return <>{isText}</>
}

CodePudding user response:

Typescript won't detect error when you decompose the object. Try to access it as an object

const ComponentA: React.FC<Props> = (prop: Props) => {
  prop.isText = false; // <- error

  return <div>{prop.isText}</div>
}

Demo

CodePudding user response:

In TypeScript, the readonly keyword is a modifier that you can add to properties in an interface to indicate that they are read-only. This means that the property can only be read and cannot be changed. However, the readonly keyword only has an effect at compile time, not at runtime. So, even if you add the readonly keyword to a property, you can still change its value in your code if you want to.

If you want to make a property truly read-only at runtime, you can use the Object.freeze() method. This method freezes an object, which means that it cannot be changed. Here's an example:

interface Props {
  readonly isText: boolean;
}

const ComponentA: FC<Props> = ({isText}: Props) {
  // Make isText truly read-only by freezing the object
  Object.freeze(isText);

  // This line will throw an error because isText is frozen
  isText = false;

  return <>{isText}</>;
}

  • Related