How to overwrite incorrect TypeScript type definition installed via @types/package

后端 未结 4 808
悲哀的现实
悲哀的现实 2020-12-02 08:28

Say that I want to use dotenv module in my TypeScript project and install its .d.ts using npm install @types/dotenv --save. Then I realize that the

4条回答
  •  孤城傲影
    2020-12-02 09:06

    A way that is not mentioned here is to put a type declaration in a index.d.ts file. For my case, the types from @types/react-bootstrap were not correct.

    I wanted to use bsClass as declared in the documentation, but it did not exist in Popover. Instead they included a prop that does not exist on Popover namely bsStyle.

    The fix for me was to remove bsStyle and add bsClass:

    import * as React from "react";
    import { Sizes } from "react-bootstrap";
    
    // Overwrite bad declaration from @types/react-bootstrap
    declare module "react-bootstrap" {
        namespace Popover {
            export interface PopoverProps extends React.HTMLProps {
                // Optional
                arrowOffsetLeft?: number | string;
                arrowOffsetTop?: number | string;
                bsSize?: Sizes;
                bsClass?: string; // This is not included in types from @types/react-bootstrap
                placement?: string;
                positionLeft?: number | string;
                positionTop?: number | string;
            }
        }
        class Popover extends React.Component { }
    }
    

    Update

    I finally bit the bullet and uploaded a PR to DefinitelyTyped for adding a few missing bsClass / bsSize declarations.

    Update 2: An example using declaration merging

    I wanted the img loading="lazy" attribute for the tag in React, but it's not merged yet. I solved it this way:

    File: global.d.ts

    // Unused import - only used to make this file a module (otherwise declare global won't work)
    // tslint:disable-next-line:no-unused
    import React from "react";
    
    // Extend HTMLImageElement to support image lazy loading
    // https://addyosmani.com/blog/lazy-loading/
    declare global {
        namespace React {
            interface ImgHTMLAttributes {
                loading?: "lazy" | "eager" | "auto";
            }
        }
    }
    

提交回复
热议问题