在带有泛型的数组中使用扩展语法时是否可以避免类型断言?

问题描述 投票:0回答:1
export type NavIconsName =
  | 'home-filled'
  | 'home-regular'
  | 'folder-filled'
  | 'folder-regular';

export interface INavLinkBase<T = {}> {
  linkName: string;
  svgIcon?: ISvgIconProps<T>;
  selectedSvgIcon?: ISvgIconProps<T>;
}

export interface ISvgIconProps<IconType> {
  iconName: IconType;
}

const shouldAddLink = true;
const navLinks: INavLinkBase<NavIconsName>[] = [
  ...(shouldAddLink ? ([
    {
      linkName: 'test4',
      svgIcon: {
        iconName: 'folder-regular'
      }
    }
  ]) as const: []),
  {
    linkName: 'test',
    svgIcon: {
      iconName: 'folder-regular'
    },
    selectedSvgIcon: {
      iconName: 'folder-filled'
    }
  }
];

另一位用户建议我可以添加

as const
来解决这个问题,但我也想避免这种情况。如果我删除它,它会抱怨
Type 'string' is not assignable to type 'NavIconsName'.(2322)
。这是不可避免的吗?

我尝试设置

as const
as INavLinkBase<NavIconsName>[]
但我想尽可能避免类型断言。

typescript typescript-generics
1个回答
0
投票

TLDR:使用

satisfies
约束

问题在于 Typescript 扩大了对象文字中的字符串和数字常量。

export type NavIconsName =
  | 'home-filled'
  | 'home-regular'
  | 'folder-filled'
  | 'folder-regular';

const icon0 = {
    iconName: 'folder-regular',
    iconSize: 20
}

type IconType0 = typeof icon0;
// type IconType0 = {
//    iconName: string;
//    iconSize: number;
//}

有 3 种方法可以改变这一点:

键入注释

type Icon = {
  iconName: NavIconsName;
  iconSize: 20 | 40;
}

const icon1: Icon = {
    iconName: 'folder-regular',
    iconSize: 20
}

常量断言

const icon2 = {
    iconName: 'folder-regular',
    iconSize: 20
} as const;

type IconType2 = typeof icon2;

//type IconType2 = {
//    readonly iconName: "folder-regular";
//    readonly iconSize: 20;
//}

满足约束

const icon3 = {
    iconName: 'folder-regular',
    iconSize: 20
} satisfies Icon;

type IconType3 = typeof icon3;

//type IconType3 = {
//    iconName: "folder-regular";
//    iconSize: 20;
//}
© www.soinside.com 2019 - 2024. All rights reserved.