1
votes

Is there any way in typescript / typescript-eslint to render an error when an optional parameter does not have a a default value? I am trying to convert my React codebase from JSX to TSX and no longer having the warnings about not having defaultProps defined is worrisome. Thanks.

bad: title does not have default prop value

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 has default prop value

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;
1

1 Answers

1
votes

This isn't something TypeScript will do for you, so there's no reliable & easy option available.

However, with a little work it is something that could be implemented as an ESLint rule. Linting rules are given the abstract syntax tree of your code (AST - a data structure describing the code of a program), and can then run checks against it, such as getting every parameter, filtering to just the optional parameters, and then checking if those all have a default value.

To actually do this, I would suggest:

Note that tslint also exists, as a purely TypeScript-focused linting tool. This may be an option, and historically this has been more popular for TS linting, but it's now deprecated in favour of eslint-typescript, so I would avoid starting with it nowadays.