首页 > 解决方案 > 打字稿:使用特定对象作为函数 arg 实现接口

问题描述

通过查看实际代码更容易解​​释这一点:

interface FooInterface {
  bar: (flags: { [key: string]: string }) => void;
}

export class Foo implements FooInterface {
  bar(flags: { myFlag: string }) {}
}

我希望任何实现FooInterface.bar传递对象的人。我不在乎钥匙。

但是,当我在Foo类中实现它并命名该键时,myFlag我收到一个错误,即该键在接口中不存在。请参阅下面的完整错误。

如何告诉 Typescript 忽略已实现类中的键?

我得到的错误:

src/extensions/test/test.provider.ts:24:3 - error TS2416: Property 'bar' in type 'Foo' is not assignable to the same property in base type 'FooInterface'.
  Type '(flags: { myFlag: string; }) => void' is not assignable to type '(flags: { [key: string]: string; }) => void'.
    Types of parameters 'flags' and 'flags' are incompatible.
      Property 'myFlag' is missing in type '{ [key: string]: string; }' but required in type '{ myFlag: string; }'.

24   bar(flags: { myFlag: string }) {}
     ~~~

标签: typescriptobjectinterface

解决方案


问题是你说myFlagmust be a string,但类型{ [key: string]: string }并不能保证myflag密钥确实存在。所以它不能满足string类型。

如果您将myFlag密钥设为可选,则它可以工作,那么您只需检查它是否存在。

interface FooInterface {
  bar: (flags: { [key: string]: string }) => void;
}

export class Foo implements FooInterface {
  bar(flags: { myFlag?: string }) {
    if (flags.myFlag) {
      console.log(flags.myFlag) // logs a string
    }
  }
}

操场


如果您想强制执行myFlag调用时提供barFoo类,那么@leonardfactory 的答案就是您所需要的。


推荐阅读