2

I'd like to use eslint to enforce the succinct syntax for optional function parameters.

I would like to use the short ? syntax in this case. That is:

// Expected syntax
function myFunct(optionalInput?: number): void {...}

// Undesired syntax
function myFunct(optionalInput: number | undefined): void {...}

Is there any way to enforce this with eslint?

1 Answer 1

3

You needn't write a custom lint rule or anything of the sort for this! There's a helpful FAQ article on the TypeScript-ESLint website that covers this:

https://typescript-eslint.io/docs/linting/troubleshooting#how-can-i-ban-specific-language-feature

You can use the playground to deduce the correct AST selector

https://typescript-eslint.io/play#showAST=es

For example - you'll want to ban FunctionDeclaration > Identifier.params > TSTypeAnnotation > TSUnionType:has(TSUndefinedKeyword)

eg - https://typescript-eslint.io/play/#ts=4.5.2&sourceType=module&showAST=es&code=PQKgUABBCmDOA2BLAdgFwsg9gWgE51V0QGNVoATbWATzQEMAPALggG1IpOByaXXTXFwA0HThADeosRFjR40UgJZcAYgFdkpRJmQARBfDq46qbcggA+CAEly0NIgBmiXkyyoAFK0wAHUzrp4AF5CNWgAXQBKADofIzoAW1hLCAAVAGVU6h9oAEFkdxMzFIyAVWQzLJymAAs6WA8y5DtnZAoAaWhqAHcBckjhKTEEuFg6AHNoZTVZCDpzX39kQIgffh8IFFgyOnIAQkHpCABfDnCwEGAwMEcNLR0IBOp1TU8pRbNA62QfNVQARhYyDUCQARrwRGIPgF4N9fqgAExAkHg3AQAA+MkIKHGkM40OWsJ+fwAzMiwbwMRANC0UBQ8VACV9iagACwAfnJqKpNOgrXpYEiLAAbphEOQJCcgA&rules=N4XyA&tsConfig=N4XyA

NOTE: the above selector isn't completely correct, and has some false-positives - but it's a good start to help you in figuring out what a selector might look like.

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

4 Comments

This is helpful advice, but in larger projects I have experienced that using no-restricted-syntax leads to problems like // eslint-disable no-restricted-syntax comments which lose any specific information about which banned syntax is being disabled for a particular file/line. This can be a good technique for evaluating a rule across a codebase, but I recommend eventually migrating to a named custom rule.
By the way, the rule as written is not quite right! :)
@jtbandes - it's not! But it's "good enough" for a quick stackoverflow answer. I almost didn't include a selector at all but I figured I'd include something to get people started.
@jtbandes As for named rules - for sure - people can definitely a custom rule for it. But likely most people don't want to go through the effort of setting up an eslint plugin locally and adding all the infra just to write one rule. The barrier-to-entry is much lower with a quick no-restricted-syntax config!

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.