Reputation: 36594
The issue is simple. I have react component which has an interface define for props. When I am passing some unknown property using the spread operator it is not giving error. I want to get that error.
interface MyProps { a: string; b: string; }
const MyComponent: React.FC = (props) => { return <></>; };
const props = { a: "a", b: "b", c: "c" };
//Giving error be Type '{ a: string; b: string; c: string; }' is not assignable to type 'IntrinsicAttributes & MyProps'.
// Property 'c' does not exist on type 'IntrinsicAttributes & MyProps
const comp1 = <MyComponent a="a" b="b" c="3"></MyComponent>;
//Not giving error while it should because c is not the valid prop
const comp2 = <MyComponent {...props}></MyComponent>;
Here is the runnable code. I have checked two github issues but they got no solution.
https://github.com/microsoft/TypeScript/issues/22144
https://github.com/microsoft/TypeScript/issues/18801
Upvotes: 4
Views: 1181
Reputation: 11
As far as I know this is by design and you won't get that error unless you also use some linting tool that looks for things like this (tools like eslint or sonarlint).
If that satisfies then you look into eslint plugin called eslint-plugin-unicorn and specifically into the rule named no-unused-properties. Maybe that will help. Here is the link to the rule: https://github.com/sindresorhus/eslint-plugin-unicorn/blob/main/docs/rules/no-unused-properties.md#disallow-unused-object-properties (I didn't test it, so no guarantees it solves the problem - just an idea to look into)
If you are concerned with the child component having access to properties that it shouldn't have access to, then I would recommend just immediately destructure the props in the child component so there is no props object there (albeit even though technically the props object would have contained the c property, typescript wouldn't allow you to access it [so props.c wouldn't be possible] without trying to get around it).
For example, instead of
const MyComponent: React.FC<MyProps> = (props) => { return <></>; };
You would have
const MyComponent: React.FC<MyProps> = ({a, b}) => { return <></>; };
This way MyComponent won't have access to any additional properties passed by the parent when using this approach.
<MyComponent {...props}></MyComponent>
Because there is no more props object to be accessed that would hold these additional properties. Typescript type checking also won't allow you to destructure any more props in the MyComponent than are defined in MyProps interface (again, without actively trying to get around it).
Don't know if that solves your problem, but this is how I get around it, so I hope it helps.
Upvotes: 1