Tìm kiếm trang web

Có cách nào để ngăn TypeScript đơn giản hóa câu lệnh `keyof` trong các tệp khai báo không?


Tôi đang cố gắng sửa một lỗi gõ phím với LitElement trên bộ trang trí @customElement của họ. Vấn đề dường như là TypeScript tối ưu hóa định nghĩa kiểu. Mã nguồn trông như sau:

export const customElement = (tagName: keyof HTMLElementTagNameMap) =>
(clazz: Constructor<HTMLElement>) => {
  window.customElements.define(tagName, clazz);
  // Cast as any because TS doesn't recognize the return type as being a
  // subtype of the decorated class when clazz is typed as
  // `Constructor<HTMLElement>` for some reason. `Constructor<HTMLElement>`
  // is helpful to make sure the decorator is applied to elements however.
  return clazz as any;
};

Nhưng trong tệp khai báo, kết quả đầu ra là như sau:

export declare const customElement: (tagName: "object" | "a" | "abbr" | "address" | "applet" | "area" | "article" | "aside" | "audio" | "b" | "base" | "basefont" | "bdo" | "blockquote" | "body" | "br" | "button" | "canvas" | "caption" | "cite" | "code" | "col" | "colgroup" | "data" | "datalist" | "dd" | "del" | "details" | "dfn" | "dialog" | "dir" | "div" | "dl" | "dt" | "em" | "embed" | "fieldset" | "figcaption" | "figure" | "font" | "footer" | "form" | "frame" | "frameset" | "h1" | "h2" | "h3" | "h4" | "h5" | "h6" | "head" | "header" | "hgroup" | "hr" | "html" | "i" | "iframe" | "img" | "input" | "ins" | "kbd" | "label" | "legend" | "li" | "link" | "map" | "mark" | "marquee" | "menu" | "meta" | "meter" | "nav" | "noscript" | "ol" | "optgroup" | "option" | "output" | "p" | "param" | "picture" | "pre" | "progress" | "q" | "rt" | "ruby" | "s" | "samp" | "script" | "section" | "select" | "slot" | "small" | "source" | "span" | "strong" | "style" | "sub" | "sup" | "table" | "tbody" | "td" | "template" | "textarea" | "tfoot" | "th" | "thead" | "time" | "title" | "tr" | "track" | "u" | "ul" | "var" | "video" | "wbr") => (clazz: Constructor<HTMLElement>) => any;

Ý tưởng là khi khai báo phần tử tùy chỉnh của bạn, bạn cũng mở rộng HTMLElementTagNameMap:

declare global {
  interface HTMLElementTagNameMap {
    'my-button': MyButton
  }
}

Có cách nào để ngăn TypeScript đơn giản hóa câu lệnh keyof trong các tệp khai báo không? Nếu tôi cập nhật thủ công tệp khai báo để sử dụng keyof, mọi thứ hoạt động như mong đợi.

Tất cả mã cho dự án này có tại https://github.com/Polymer/lit-element