Home > Software design >  Purpose of '@typescript-eslint/no-non-null-assertion' when disabling a button
Purpose of '@typescript-eslint/no-non-null-assertion' when disabling a button

Time:03-01

In this block of code, what is the .value! and @typescript-eslint/no-non-null-assertion doing? The documentation is too abstract for me to connect to the context of this button behavior.

const submitButton = ref<HTMLButtonElement | null>(null);

  //Disable button
  /* eslint-disable  @typescript-eslint/no-non-null-assertion */
  submitButton.value!.disabled = true;

P.S. Only in programming can you say "no-non-null" with a straight face.

CodePudding user response:

The ! is a typescript non-null assertion. It tells typescript "I know it looks like value might be a null, but trust me, it's not". This can be useful if you know something that typescript does not (in this case, you presumably know that the ref will be populated before this code runs), but it essentially turns off type checking on this line, and so can accidentally introduce bugs.

Since the non-null assertion is risky, there is a lint rule which can be used to ban their use. The lint rule, when enabled, will flag this line as a problem. The typical fix would be to then write code to check for null, so that no assertion is needed. But if you want to, you can tell eslint not to check this line, via a special comment like /* eslint-disable @typescript-eslint/no-non-null-assertion */.

So in summary, these lines are saying "Hey typescript, don't check this. Hey eslint, don't check this".

  • Related