忽略打字稿定义错误

Ignore typescript definition error

我有一个第 3 方打字稿定义文件 (JayData):

declare module MyEntities
{
    export class Container extends $data.EntityContext
    {
        public onReady(): $data.IPromise<any>;
        public onReady(handler: (context: Container) => void): $data.IPromise<any>;

        public Users: $data.EntitySet<Models.UserModel>;
    }
}

但是 Javascript 的一个有效部分是如何初始化 MyEntities 类:

var db = new MyEntities({ name: 'local', databaseName: 'MyDb' });

但是对于 TS 这没有意义,MyEntities 是一个模块而不是一个类,因此抛出编译错误:Cannot invoke an expression whose type lacks a call signature.

有什么办法可以忽略这个编译错误吗?

Is there any way around this to ignore this compile error?

UGLY 修复 使用 TypeAssertion:

declare module $data{
    export class EntityContext{}
    export class IPromise<T>{}
    export class EntitySet<T>{}
}
declare module Models{export class UserModel{}}


declare module MyEntities
{
    export class Container extends $data.EntityContext
    {
        public onReady(): $data.IPromise<any>;
        public onReady(handler: (context: Container) => void): $data.IPromise<any>;

        public Users: $data.EntitySet<Models.UserModel>;
    }
}

var db = new ((<any>MyEntities)({ name: 'local', databaseName: 'MyDb' }));

正确修复

你的类型定义有很多错误。您需要回顾一下 TypeScript 的强大功能 interface。这是一个让您入门的示例:

interface Container{
    onReady():any;
}
interface ContainerStatic{
    new ():Container;
}

declare var MyEntities:
{
    // A constructor signature
    new (options:any):any; 

    // Sub classes 
    Container:ContainerStatic;
}

var db = new MyEntities({ name: 'local', databaseName: 'MyDb' });
var container = new MyEntities.Container();

当您处理自动生成的定义时,您可能会发现这个技巧很有用。

您可以使用模块合并来解决您的问题,而无需编辑自动生成的文件。

首先包含此定义文件,它将合并到自动生成的文件中以创建合并的 "class module"。 (对于定义文件,顺序并不像您在实际实现代码中尝试使用模块合并那么重要)。

myextension.d.ts

declare class MyEntities {
    constructor(options: { name: string; databaseName: string; })
}

两个声明必须具有相同的共同根(这将导致它们合并),但查看您问题中的定义似乎对您有用。

如果无法正确修复错误或使用已经建议的更合适的解决方法,从 TypeScript 2.6(2017 年 10 月 31 日发布)开始,现在 a way to ignore all errors from a specific line 使用 // @ts-ignore在目标行之前评论。

The mendtioned documentation 已经够简洁了,但要回顾一下:

// @ts-ignore
const s : string = false

禁用此行的错误报告。

但是,只有在修复错误或使用像 (x as any) 这样的 hack 比丢失一行的所有类型检查要麻烦得多时,才应将其用作最后的手段。

至于指定某些错误,讨论了当前(2018 年年中)状态 here, in Design Meeting Notes (2/16/2018) and further comments,基本上是

"no conclusion yet"

并强烈反对引入这种微调。