忽略打字稿定义错误

时间:2015-01-07 03:50:58

标签: typescript jaydata

我有第三方打字稿定义文件(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

有没有办法忽略这个编译错误?

3 个答案:

答案 0 :(得分:2)

  

有没有办法忽略这个编译错误?

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();

答案 1 :(得分:2)

从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时,此方法才是万不得已的方法,这比丢失一行的所有类型检查要麻烦得多。

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

  

“还没有结论

强烈反对引入这种微调。

答案 2 :(得分:1)

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

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

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

myextension.d.ts

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

这两个声明必须具有相同的公共根(这将导致它们合并),但是查看问题中的定义看起来它会对你有效。