如何解决解析通用属性名称
我正在尝试使用通用属性名称创建对象
type ColorStyle<T extends string> = Record<ColorType,Record<T,string>>;
function getColorStyle<T extends string>(propertyName: T): ColorStyle<T> {
return {
accent: { [propertyName]: colors.accent },primary: { [propertyName]: colors.primary },secondary: { [propertyName]: colors.secondary },tertiary: { [propertyName]: colors.tertiary },black: { [propertyName]: colors.black },white: { [propertyName]: colors.white },gray: { [propertyName]: colors.gray },gray2: { [propertyName]: colors.gray2 },}
}
我遇到的错误是
键入'{[x:字符串]:字符串; }”不可分配给“ Record
我想像这样使用它
const colorStyle = getColorStyle('color');
const primaryColor = colorStyle.primary.color;
const backgroundColorStyle = getColorStyle('backgroundColor');
const primaryBackgroundColor = backgroundColorStyle.primary.backgroundColor;
编辑:
export const colors = {
accent: "#F3534A",primary: "#0AC4BA",secondary: "#2BDA8E",tertiary: "#FFE358",black: "#323643",white: "#FFFFFF",gray: "#9DA3B4",gray2: "#C5CCD6"
};
export type ColorType = keyof typeof colors;
解决方法
我认为问题出在打字稿将您的身体{ [propertyName]: colors.accent }
推断为{ [x: string]: string }
的方式与{ [P in string]: string } (Record<string,string>)
不同。但是它允许您强制转换{ [propertyName]: colors.accent } as Record<T,string>
,这意味着您可以简单地将结果强制转换为返回值:
投射单个项目:
return {
accent: { [propertyName]: colors.accent } as Record<T,string>,// ...
}
或者您可以投射整个对象:
return {
accent: { [propertyName]: colors.accent },// ...
} as ColorStyle<T>
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。