![](/img/trans.png)
[英]typescript/eslint rule for function syntax in objects implementing interface
[英]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
时提供myFlag
是Foo
class,那么@leonardfactory 的答案就是您所需要的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.