Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make React Props Readonly in Typescript

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}</>
}
like image 541
Pytan Avatar asked Mar 02 '26 04:03

Pytan


1 Answers

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

like image 175
Sachila Ranawaka Avatar answered Mar 05 '26 09:03

Sachila Ranawaka