[Typescript] Partial autocompletion (string & {})
const presetSizes = {
xs: "0.5rem",
sm: "1rem",
};
type Size = keyof typeof presetSizes;
//type LooseSize = Size | string; // the result will be string
type LooseSize = Size | (string & {}); // working
export const Icon = (props: { size: LooseSize }) => {
return (
<div
style={{
width:
props.size in presetSizes
? presetSizes[
/**
* The 'as' is necessary here because TS can't seem to narrow
* props.size to Size properly
*/
props.size as Size
]
: props.size,
}}
/>
);
};
<>
<Icon size="sm"></Icon>
<Icon size="xs"></Icon>
<Icon size="10px"></Icon>
</>;