【问题标题】:TypeScript interface implementation errorTypeScript 接口实现错误
【发布时间】:2014-10-10 07:11:46
【问题描述】:

我很难协调以下文件的情况:

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 类型,因为我想尽可能明确,我必须从 .d.ts 文件中取出规范能够在子类中实现接口和专门化实现。这似乎是一个错误。我该如何解决这个问题?

【问题讨论】:

标签: interface compiler-errors typescript overloading subclass


【解决方案1】:

只需输入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

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

【讨论】:

  • 是的,这就是我最终所做的。不知道这是允许的,尽管必须输入any 有点令人困惑。
  • 它是必需的,因为 inside 函数体你可以执行 chuck.foo 并且编译器不会给你一个错误,因为它认为它的 any。因此,如果您使用--noImplicitAny,则需要明确
猜你喜欢
  • 2023-03-04
  • 1970-01-01
  • 2016-06-20
  • 1970-01-01
  • 2020-04-06
  • 1970-01-01
  • 2023-03-13
  • 2021-07-20
相关资源
最近更新 更多