How to disable a ts rule for a specific line?

后端 未结 2 1087
感情败类
感情败类 2021-02-04 22:46

Summernote is a jQuery plugin, and I don\'t need type definitions for it. I just want to modify the object, but TS keeps throwing errors. The line bellow still gives me:

相关标签:
2条回答
  • 2021-02-04 23:32

    You can use /* tslint:disable-next-line */ to locally disable tslint. However, as this is a compiler error disabling tslint might not help.

    You can always temporarily cast $ to any:

    delete ($ as any).summernote.options.keyMap.pc.TAB
    

    which will allow you to access whatever properties you want.


    Edit: As of Typescript 2.6, you can now bypass a compiler error/warning for a specific line:

    if (false) {
        // @ts-ignore: Unreachable code error
        console.log("hello");
    }
    

    Note that the official docs "recommend you use [this] very sparingly". It is almost always preferable to cast to any instead as that better expresses intent.

    0 讨论(0)
  • @ts-expect-error

    TS 3.9 introduces a new magic comment. @ts-expect-error will:

    • have same functionality as @ts-ignore
    • trigger an error, if actually no compiler error has been suppressed (= indicates useless flag)
    if (false) {
      // @ts-expect-error: Let's ignore a single compiler error like this unreachable code 
      console.log("hello"); // compiles
    }
    
    // If @ts-expect-error didn't suppress anything at all, we now get a nice warning 
    let flag = true;
    // ...
    if (flag) {
      // @ts-expect-error
      // ^~~~~~~~~~~~~~~^ error: "Unused '@ts-expect-error' directive.(2578)"
      console.log("hello"); 
    }
    

    Alternatives

    @ts-ignore and @ts-expect-error can be used for all sorts of compiler errors. For type issues (like in OP), I recommend one of the following alternatives due to narrower error suppression scope:

    ▶ Use any type

    // type assertion for single expression
    delete ($ as any).summernote.options.keyMap.pc.TAB;
    
    // new variable assignment for multiple usages
    const $$: any = $
    delete $$.summernote.options.keyMap.pc.TAB;
    delete $$.summernote.options.keyMap.mac.TAB;
    

    ▶ Augment JQueryStatic interface

    // ./global.d.ts
    interface JQueryStatic {
      summernote: any;
    }
    
    // ./main.ts
    delete $.summernote.options.keyMap.pc.TAB; // works
    

    In other cases, shorthand module declarations or module augmentations for modules with no/extendable types are handy utilities. A viable strategy is also to keep not migrated code in .js and use --allowJs with checkJs: false.

    0 讨论(0)
提交回复
热议问题