我有一个带有 React 组件的 JS 对象,按 ID 索引。
const MODAL_ENTITIES = {
changeEmail: ChangeEmailModal,
changeUsername: ChangeUsernameModal,
};
我想要一个 ModalEntity
类型,结果如下:
type ModalEntity = {
id: 'changeEmail',
props: React.ComponentProps<typeof ChangeEmailModal>
} | {
id: 'changeUsername',
props: React.ComponentProps<typeof ChangeUsernameModal>
};
我的问题是,我希望从 MODAL_ENTITIES
对象动态生成类型,因为我希望添加模式的过程尽可能轻松。
有没有办法动态定义这种类型?我可以这样做,但我想避免泛型,我希望推断出 T
:
export type ModalEntity<T extends keyof typeof MODAL_ENTITIES> = {
id: T;
props: React.ComponentProps<typeof MODAL_ENTITIES[T]>;
};
最佳答案
我做了一个模型。我们的想法是从 ModalEntity
类型中获取通用 T
,以便在添加新模态时可以轻松使用它。
模态框的占位符,假设每个模态框都有不同的属性:
import React from 'react';
const ChangeEmailModal: React.FC<{ id: string; name: string; email: string }> = ({ id, ...props }) => {
return (
<div id={id}>
{props.name} {props.email}
</div>
);
};
const ChangeUsernameModal: React.FC<{ id: string; otherName: string; username: string }> = ({ id, ...props }) => {
return (
<div id={id}>
{props.otherName} {props.username}
</div>
);
};
const MODAL_ENTITIES = {
changeEmail: ChangeEmailModal,
changeUsername: ChangeUsernameModal
};
然后我们以动态方式从您的 MODAL_ENTITIES
获取 key :
export type ModalEntities = typeof MODAL_ENTITIES;
// this gets all the keys in type ModalEntities
type StringKeys<T> = {
[k in keyof T]: k;
}[keyof T];
type ModalEntitiesKeys = StringKeys<ModalEntities>;
最后:
export type ModalEntity = {
[K in ModalEntitiesKeys]: {
id: K;
props: React.ComponentProps<typeof MODAL_ENTITIES[K]>;
};
}[ModalEntitiesKeys];
ModalEntity
类型将如下所示,并且不再是通用的。无论模态 props 不同,props
字段的类型都会根据您的请求动态推断。
type ModalEntity = {
id: "changeEmail";
props: {
id: string;
name: string;
email: string;
} & {
children?: React.ReactNode;
};
} | {
id: "changeUsername";
props: {
id: string;
otherName: string;
username: string;
} & {
children?: React.ReactNode;
};
}
您可以详细阐述这个想法。
关于javascript - Typescript 动态从对象推断类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71644836/