我使用的是TypeScript 4.9.5
,我需要利用类型重新映射.在重新映射过程中,我希望保持optional property mode
.具体地说,我需要将接口的每个属性转换为add a "child" prefix
,并将属性的原始文本类型转换为大写.以下是我的接口定义:
interface ChildrenProps {
children: ReactNode;
className?: string;
style?: CSSProperties;
}
我希望将其转换为以下形式:
interface ChildrenPropsWithPrefix {
childChildren: ReactNode;
childClassName?: string;
childStyle?: CSSProperties;
}
为了实现这一点,我编写了以下类型实用程序:
/** Make all properties with a prefix and convert the first character of properties to uppercase */
type PrefixAll<T, P extends string> = {
[K in keyof T & string as `${P}${Capitalize<K>}`]: T[K];
}
然而,我得到的结果如下:
interface ChildrenPropsWithPrefix {
childChildren: ReactNode;
childClassName: string;
childStyle: CSSProperties;
}
正如你可能注意到的,这个结果和我预期的结果是不同的.所有的属性都变成了required
,TS Playground link,而我希望它们变成remain optional
.
虽然我可以通过设置ParentProps extend Partial\<PrefixAll\<ChildrenProps, 'child'\>\>
来解决这个问题,但它改变了界面的原始 struct ,这可能会让其他开发人员感到困惑.我想要避免这样的情况.
你能建议一个解决方案或替代方法,让我在保持可选物业模式的同时达到预期的结果吗?如果您能提供任何代码示例或见解,我将不胜感激.