简体   繁体   English

Typescript参数数量错误

[英]Typescript number of arguments error

Quick question and I'm sure someone will have a quick answer for this one. 快速的问题,我相信有人会得到一个快速的答案。

I am trying to use document. 我正在尝试使用文档。

document.createElement("button", "option");

typescript does not like this due to the second argument, it complains that it is only expecting one argument not two to be passed. 由于第二个参数,typescript不喜欢这个,它抱怨它只是期望一个参数而不是两个被传递。 In vanilla JS two arguments are acceptable. 在vanilla JS中,有两个论点可以接受。

How can I get the typescript compiler to allow this? 如何让typescript编译器允许这个?

It does look like the standard definition does not allow for this, and seems to be wrong. 它确实看起来像标准定义不允许这样,似乎是错误的。

I guess a bug on github would be in order. 我猜github上的一个bug会有序。

In the meantime as a hack you can save the function with another type. 在此期间,您可以使用其他类型保存该功能。 For example. 例如。

let createElement: (tagname: string, options: string) => HTMLElementTagNameMap = document.createElement;

According to the standard , the second argument should be an object with a single is property, not a string. 根据标准 ,该第二参数应该是与单个对象is属性,而不是字符串。 So, theoretically, that line should be: 所以,从理论上讲,该行应该是:

document.createElement("button", { is: "option" });

The use of a string was part of an older spec and is deprecated, although supported by Chrome. 使用字符串是较旧规范的一部分,虽然受Chrome支持,但已弃用。

In any case, that overload is not in lib.d.ts , so you'll need to overload that definition yourself as @NitzanTomer describes , and/or create an issue at TypeScript's GitHub repo explaining the issue . 在任何情况下,该重载都不在lib.d.ts中 ,因此您需要在@NitzanTomer描述时自己重载该定义 ,和/或在TypeScript的GitHub 仓库中创建一个解释该问题的问题

Note that the overload of createElement you are attempting to use is part of the Custom Elements spec, which as of this writing is a Working Draft, and thus the TypeScript maintainers would likely not support adding it to lib.d.ts. 请注意,您尝试使用的createElement的重载是Custom Elements规范的一部分,在撰写本文时,它是一个工作草案,因此TypeScript维护者可能不支持将其添加到lib.d.ts.

It's missing from the definitions, but you can easily add it: 定义中缺少它,但您可以轻松添加它:

interface Document {
    createElement(tagName: string, options?: string | { is: string });
}

If you are using a module system (you import/export) then you need to do it like so: 如果您使用的是模块系统(导入/导出),那么您需要这样做:

declare global {
    interface Document {
        createElement(tagName: string, options?: string | { is: string });
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM