为什么声明类型 用未知方法解决错误? (打字稿)

问题描述 投票:0回答:1

我有这个代码:

this.$(<string> button.className + ' input').bootstrapToggle('on');

打字稿给了我这个错误:

error TS2339: Property 'bootstrapToggle' does not exist on type 'JQuery<HTMLElement>'.

我用这个成功修复了错误:

(<any> this.$(<string> button.className + ' input')).bootstrapToggle('on');

为什么声明元素为'any'类型可以解决此错误?

javascript jquery typescript
1个回答
1
投票

这是因为bootstrapToggle没有在jquery的声明文件中定义。

尝试通过在项目的.d.ts文件中添加此类型的声明来添加此定义

interface BootstrapToggleOptions {
    on?: string;

    off?: string;

    onstyle?: OnOffStyle;

    offstyle?: OnOffStyle;

    size?: Size;

    width?: number;

    height?: number;
}

type OnOffStyle = "default" | "primary" | "success" | "info" | "warning" | "danger";
type Size = "large" | "normal" | "small" | "mini";

interface JQuery {
    bootstrapToggle(): JQuery;

    bootstrapToggle(options?: BootstrapToggleOptions): JQuery;
}

使用(<any> this.$(<string> button.className + ' input')) hack,不建议它打败打字点。

© www.soinside.com 2019 - 2024. All rights reserved.