[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>
</>;

 

posted @ 2023-08-04 19:44  Zhentiw  阅读(5)  评论(0编辑  收藏  举报