TypeScript接口实现错误

时间:2014-08-17 00:25:49

标签: interface compiler-errors typescript overloading subclass

我很难协调以下文件的内容:

interface T {
  _t(chunk: Array<string>): void;
  _t(chunk: string): void;
}

class TT implements T {
  _t(chunk: string): void {}
}

当我尝试编译它时,我收到以下错误消息:

Types of property '_t' of types 'TT' and 'T' are incompatible:
    Call signatures of types '(chunk: string) => void' and 
      '{ (chunk: string[]): void; (chunk: string): void; }' are incompatible:
        Type 'String' is missing property 'join' from type 'string[]'.

这很好,这意味着我应该能够通过明确指定属性的对象类型来解决问题吗?

interface T {
  _t(chunk: Array<string>): void;
  _t(chunk: string): void;
}

class TT implements T {
  _t: {
    (chunk: string): void;
    (chunk: Array<string>): void;
  } = function(chunk) {};
}

现在,当我使用--noImplicitAny进行编译时出现问题,我收到以下错误消息:

error TS7012: Parameter 'chunk' of lambda function implicitly has an 'any' type.

似乎无论我做什么我都输了,因为如果我对界面上的类型规范小心并拼出一切,那么我就不能将实现专门化为只有一种类型。问题是有.d.ts个文件正是这样做的,如果我希望编译器找到所有any类型,因为我希望尽可能明确,我必须从{{ {1}}文件既能实现接口又能专门化子类中的实现。这似乎是一个错误。我该如何解决这个问题?

1 个答案:

答案 0 :(得分:2)

只需输入chunk:any

interface T {
  _t(chunk: Array<string>): void;
  _t(chunk: string): void;
}

class TT implements T {
  _t: {
    (chunk: string): void;
    (chunk: Array<string>): void;
  } = function(chunk:any) {};
}

// Safety: 
var t = new TT();
t._t(''); // okay
t._t([]); // okay
t._t(true); // Error

请注意,它不会降低您的类型安全性^