I am currently trying to create a React Hook that returns a CSS style object with a few properties. But the error appears and I don't know why, but I suppose it is because the object is too complex to be evaluated, or am I completely wrong?
Error Message
Expression produces a union type that is too complex to represent. ts(2590)
import React from 'react';
interface Test {
color?: string;
backgroundColor?: string;
border?: string;
}
export const func = (prop: Test): React.CSSProperties => {
const result: React.CSSProperties = {};
for (const some in prop) {
const key = some as keyof Test;
result[key] = prop[key]; // Expression produces a union type that is too complex to represent. ts(2590)
}
return result;
};
If the Test interface has only one or two properties, no problem appear. But with 3 or more, there is the error. Although the react app runs normally, and even the returned result when applied shows the correct styles. It's annoying and I can just ignore, but I would like to understand why this is happening and if there is a way to resolve it other than disable typescript for that line.
PS: The project was created using Vite and is running on React v18
and Typescript v4.6.3
Try this:
interface Test {
color?: string;
backgroundColor?: string;
border?: string;
}
type TestKey = keyof Test;
export function func<T extends CSSProperties>(property: T): T {
const result = {} as T;
// eslint-disable-next-line guard-for-in
for (const some in property) {
const key = some as keyof T;
result[key] = property[key];
}
return result;
}
As I understand it, the problem is that the Test interface doesn't have exactly the same origin as CSSProperties, even though it looks like it does... By creating a generic function, I was able to force this, since we were able to extend Test as being CSSProperties