【发布时间】:2021-03-02 19:20:15
【问题描述】:
我正在寻找一种类型安全的方法来在对象之间复制属性。我的代码在 javascript 中工作,我正在尝试将其转换为打字稿,但是我无法让它工作。我收到Type '' is not assignable to type 'undefined'.(2322)
有人可以帮助我了解是否可以做我想做的事情以及我错过了什么?
enum Kind { PRIMARY, SECONDARY };
enum Size { SMALL, MEDIUM };
type IconProps = { kind: Kind; size: Size; };
type ButtonProps = { id: string; text: string; onClick: () => void; };
type Props = ButtonProps & IconProps;
function iconComponent(props: Partial<IconProps>) {}
function buttonComponent(props: Partial<ButtonProps>) {}
const isIconProp = (key: string): key is keyof IconProps => /^(kind|size)$/.test(key);
const isButtonProp = (key: string): key is keyof ButtonProps => /^(id|text|onClick)$/.test(key);
function initComponents(props: Partial<Props>) {
// Default values
const icon: Partial<IconProps> = {
kind: Kind.PRIMARY
};
const button: Partial<ButtonProps> = {
id: 'button'
};
// How to iterate through keys and assign properties to respective objects?
Object.keys(props).forEach(key => {
// Why is this not working?
if (isIconProp(key)) {
icon[key] = props[key]
}
if (isButtonProp(key)) {
button[key] = props[key];
}
// This works
if (key === 'kind') {
icon.kind = props.kind;
}
if (key === 'onClick') {
button.onClick = props.onClick;
}
});
return {
root: buttonComponent(button),
child: [iconComponent(icon)]
};
}
【问题讨论】:
-
我认为您无法在运行时
key is keyof IconProps中执行此操作,因为这不是实际的 javascript。您可以找到它们是图标道具还是按钮道具的一种方法是检查属性名称。例如。是道具种类,或者尺寸,那么你就知道它的图标道具了。 -
@medzz123 谢谢.. 正如我所提到的,代码在运行时运行良好。我只是想用打字稿对代码进行静态类型检查。我已经更新了代码以使其清晰。
标签: javascript reactjs typescript react-typescript