I have defined a custom TypeScript type as follows:
export type Milliseconds = number & { __type: 'milliseconds' };
and I want to restrict the usage of the division operator on this type, like so:
const foo = 1 as Milliseconds;
const bar = foo / 2;
To achieve this, I have created an ESLint rule:
"no-restricted-syntax": [
"error",
{
"selector": "BinaryExpression[left.typeAnnotation.typeName.name='Milliseconds'][operator='/']",
"message": "Milliseconds cannot be divided directly, please use the msDivide()."
},
],
However, the rule only works when casting to milliseconds right before dividing, resulting in an error for this scenario:
const foo = 1;
const bar = foo as Milliseconds / 2;
But it does not work for this case:
const foo = 1 as Milliseconds;
const bar = foo / 2;
After experimenting with the AST using:
,
it appears that the issue lies in the representation of the typeAnnotation in the identifier for foo
.
Is there a way to write a selector that can infer the type of left
based on its name?