reactjs - 在 TypeScript 中应用 React 组件道具的严格推理/形状
问题描述
我目前面临一个问题,我想让我的 React 组件更加严格。我使用带有 React、GraphQL 和 TypeScript 的堆栈,并且使用了很多片段。与 TypeScript 一起工作的一件事是片段的类型推断,它缩小了我可以使用的对象属性(类型)。
问题是,如果我更新我的组件,在某些时候,我无法限制我在组件中需要的严格的最低属性。我的意思是,我可以手动完成,但可能会很痛苦。如果您不明白,我将向您展示以下示例:
给定消耗片段的组件:
type VehicleViewFragment = {
name: string;
createdAt: Date;
}
type Props = {
vehicle: VehicleViewFragment;
enabled: boolean;
};
const VehicleView = ({ vehicle, enabled }: Props) => {
return (
<div>
<div>{vehicle.name}</div>
<div>{vehicle.createdAt}</div>
{enabled && <button>Ok</button>}
</div>
)
}
这是一个相当简单的组件。当我在我的组件中使用一个新属性时,TypeScript 会给我一个错误,说它不存在,所以我需要更新我的片段(如果这个属性还不存在,可能还有我的 GraphQL 服务器)。
没关系,那另一种方式呢,如果这个组件看起来像这样:
type VehicleViewFragment = {
name: string;
createdAt: Date;
}
type Props = {
vehicle: VehicleViewFragment;
enabled: boolean;
};
const VehicleView = ({ vehicle, enabled }: Props) => {
return (
<div>
<div>{vehicle.name}</div>
{enabled && <button>Ok</button>}
</div>
)
}
createdAt
不再需要,但我需要手动检查我的片段以删除该属性。是否可以动态推断 Props 的类型并在消费的片段和原始片段类型之间进行严格检查?
想象一下:
type VehicleViewFragment = {
name: string;
createdAt: Date; // this property is never used so an error should be displayed...
}
type Props = {
vehicle: VehicleViewFragment;
enabled: boolean;
};
type InferedProps = {
vehicle: {
name: string; // or `any` if we can't infer the type from usage
}
enabled: boolean;
}
const VehicleView = ({ vehicle, enabled }: Props) => {
return (
<div>
<div>{vehicle.name}</div>
{enabled && <button>Ok</button>}
</div>
)
}
这样如果 Props 的结构 !== InferedProps,TypeScript 会抛出异常并显示两种类型之间的差异。所以现在我很容易检测到一个字段何时无用,并且很容易从相关片段中删除它。
解决方案
推荐阅读
- java - 多个消费者和批量读取的恰好一次交付
- javascript - 如何在一个指令上使用多个 ngFor 进行属性绑定
- java - JavaFX 从字节中读取视频
- r - 如何/何时在 R 中设置 HOME 环境变量
- oracle - PL/SQL 将函数的返回变量存储在布尔变量中
- excel - 根据特定前提计算两个日期之间的天数
- ruby-on-rails - ActiveStorage 中的文件未显示“缺少模板”错误
- php - 标头后丢失会话
- javascript - React/Redux:一个用于多个输入字段的 onChange 处理程序
- api - Consul KV 数据存储 http api 写入获取锁和释放会话