I have a problem with typescript that say my property isn’t compatible, but I think it is
- Types of property ‘size’ are incompatible.
- Type ‘string’ is not assignable to type ‘"s" | "m" | "l" | "xl" | undefined’.ts(2322)
How can I fix it ?
./src/components/App
function App() {
const params = {
label: 'Select',
placeholder: 'Placeholder',
isRequired: true,
offset: { X: '0', Y: '100%' },
zIndex: 10,
size: 's',
classes: ['class1', 'class2', 'class3', 'class4', 'class5'],
};
return <SelectMenu params={params} />;
}
./src/components/SelectMenu
function SelectMenu({
params: {
label,
placeholder,
isRequired = false,
offset = { X: '0', Y: '100%' },
zIndex = 0,
size = 'm',
classes,
},
}: {
params: {
label?: string;
placeholder?: string;
isRequired?: boolean;
offset?: { X: string; Y: string };
zIndex?: number;
size?: 's' | 'm' | 'l' | 'xl';
classes?: string | string[];
};
})
edit :
I want it to work like that : is this possible ?
const params = {
label: 'Select',
placeholder: 'Placeholder',
isRequired: true,
offset: { X: '0', Y: '100%' },
zIndex: 10,
size: 's',
classes: ['class1', 'class2', 'class3', 'class4', 'class5'],
};
return <SelectMenu {...params} />;
type Params = {
label?: string;
placeholder?: string;
isRequired?: boolean;
offset?: { X: string; Y: string };
zIndex?: number;
size?: 's' | 'm' | 'l' | 'xl';
classes?: string | string[];
};
function SelectMenu({
label,
placeholder,
isRequired = false,
offset = { X: '0', Y: '100%' },
zIndex = 0,
size = 'm',
classes,
}: Params)
2
Answers
if you look at the type of
params
after you declare it you can see has literal types widened and isso you can either case individual fields to their literal type
size: 'm' as 'm'
or can addas const
to the objectwhich gives types
Or if you don’t want to do that if you create
params
inline in the component render it should accept ithope that helps
You can try to use a
const
assertion (as const
):But note it will affect the resulting type quite a bit, as stated in the docs:
Or
satiesfies
:Which doesn’t affect the resulting type as much (probably closest to what you want, IMO):
Here you can see the difference between using both: