javascript - 检查 Typescript 中的默认值
问题描述
当可选参数没有默认值时,typescript / typescript-eslint 有什么方法可以呈现错误?我正在尝试将我的 React 代码库从 JSX 转换为 TSX,并且不再有关于defaultProps
未定义的警告令人担忧。谢谢。
坏:标题没有默认的道具值
import * as React from 'react';
interface Props {
title?: string;
}
const SampleComponent: React.FC<Props> = ({ title }) => (
<h1>
{title && <p>{title}</p>}
</h1>
);
export default SampleComponent;
好:标题有默认的道具值
import * as React from 'react';
interface Props {
title?: string;
}
const SampleComponent: React.FC<Props> = ({ title = 'foo' }) => (
<h1>
{title && <p>{title}</p>}
</h1>
);
export default SampleComponent;
解决方案
这不是 TypeScript 会为您做的事情,因此没有可靠且简单的选项可用。
然而,只要做一些工作,它就可以作为 ESLint 规则来实现。Linting 规则给出了代码的抽象语法树(AST - 一种描述程序代码的数据结构),然后可以对其进行检查,例如获取每个参数,仅过滤可选参数,然后检查是否这些都有一个默认值。
要真正做到这一点,我建议:
- 在你的项目中使用ESLint-TypeScript 插件设置ESLint
- 阅读这篇关于编写自定义 ESLint 规则的介绍:https ://blog.yonatan.dev/writing-a-custom-eslint-rule-to-spot-undeclared-props/ (请注意,这是查看 JavaScript AST,而不是TypeScript,但非常相似,纯 JS 是一个很好的起点)
- 查看简单的现有 TS linting 规则,例如no-parameter-properties(构造函数参数上没有
private
/public
/etc 属性),并确保您了解它们的工作原理 - 尝试编写自己的
请注意,tslint 也存在,作为一个纯粹的以 TypeScript 为中心的 linting 工具。这可能是一种选择,从历史上看,这在 TS linting 中更受欢迎,但现在它已被弃用,取而代之的是 eslint-typescript,所以我现在会避免从它开始。
推荐阅读
- jquery - 网页上聊天机器人的动态高度和宽度
- ios - MicroBlink SDK 的 USDL 组合识别器 documentDataMatch 总是返回 true
- python - 如何将列标签转换为列中的值?
- sqlite - 在我的 INSERT INTO 语句中运行 COUNT 时遇到问题
- regex - 如何使用 different_url+last_part 添加 nginx rewrite url+last_part?
- java - java.sql.SQLException:不能为 SELECT 发出 executeUpdate() 或 executeLargeUpdate()
- c# - 如何使用 C# 在 ASP.NET 中将下拉列表与 Web 服务绑定
- javascript - 选择整个字典的值
- python - 如何使用 python 在 EventHub 消息中发送属性详细信息?
- css - 如何从代码库中摇树未使用的样式