eslint rule to enforce Typescript optional parameter function syntax

Viewed 589

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 Answers

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.

Related