簡體   English   中英

typescript:使用特定對象作為 function arg 實現接口

[英]typescript: implementing an interface using specific objects as a function arg

通過查看實際代碼更容易解釋這一點:

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

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

我希望任何實現FooInterface.bar的人都能通過 object。 我不在乎鑰匙。

但是,當我在Foo class 中實現它並將密鑰命名為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 }) {}
     ~~~

使用泛型類型,您可以強制標志為帶有字符串值的 object,然后在 class 實現中指定類型:

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

type BarFlags = { myFlag: string };

export class Foo implements FooInterface<BarFlags> {
  bar(flags: BarFlags) {}
}

游樂場鏈接

問題是您說myFlag必須是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
    }
  }
}

操場


如果您想強制在調用bar時提供myFlagFoo class,那么@leonardfactory 的答案就是您所需要的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM