1

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

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

FYI I realized I misspoke and I am, infact, using typescript-eslint, and not ts-lint. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.