【问题标题】:Checking for default values in Typescript检查 Typescript 中的默认值
【发布时间】:2019-12-02 02:16:57
【问题描述】:

当可选参数没有默认值时,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;

good:title 有默认的 prop 值

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;

【问题讨论】:

    标签: javascript reactjs typescript eslint typescript-eslint


    【解决方案1】:

    TypeScript 不会为你做这件事,因此没有可靠且简单的选项可用。

    不过,只要做一些工作,它就可以作为 ESLint 规则来实现。 Linting 规则给出了代码的抽象语法树(AST - 一种描述程序代码的数据结构),然后可以对其进行检查,例如获取每个参数,仅过滤可选参数,然后检查是否这些都有一个默认值。

    要真正做到这一点,我建议:

    请注意,tslint 也存在,它是一个纯粹以 TypeScript 为中心的 linting 工具。这可能是一个选项,从历史上看,这在 TS linting 中更受欢迎,但它是 now deprecated 支持 eslint-typescript,所以我现在会避免从它开始。

    【讨论】:

    • 仅供参考,我意识到我说错了,事实上,我使用的是 typescript-eslint,而不是 ts-lint。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-01
    • 1970-01-01
    • 2016-05-06
    • 2022-11-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多