[英]typescript: implementing an interface using specific objects as a function arg
It's easier to explain this by looking at the actual code:通过查看实际代码更容易解释这一点:
interface FooInterface {
bar: (flags: { [key: string]: string }) => void;
}
export class Foo implements FooInterface {
bar(flags: { myFlag: string }) {}
}
I want anyone who implements FooInterface.bar
to pass an object.我希望任何实现
FooInterface.bar
的人都能通过 object。 I don't care about the keys.我不在乎钥匙。
However, when I implemented it in Foo
class and I named the key as myFlag
I got an error that this key doesn't exist in the interface.但是,当我在
Foo
class 中实现它并将密钥命名为myFlag
,我收到一个错误,即该密钥在接口中不存在。 See the complete error below.请参阅下面的完整错误。
How do I tell Typescript to ignore the keys in the implemented classes?如何告诉 Typescript 忽略已实现类中的键?
The error I got:我得到的错误:
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 }) {}
~~~
Using generic typings, you can force the flags to be an object with string values, then specify the type in the class implementation:使用泛型类型,您可以强制标志为带有字符串值的 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) {}
}
The problem is that you are saying myFlag
must be a string
, but the type { [key: string]: string }
does not guarantee that the myflag
key actually exists.问题是您说
myFlag
必须是string
,但类型{ [key: string]: string }
并不能保证myflag
键确实存在。 So it cannot satisfy the string
type.所以它不能满足
string
类型。
If you make the myFlag
key optional it works, you then just have to check it for existence.如果您将
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
}
}
}
If you want to enforce that myFlag
is provided when you call bar
is the Foo
class, then @leonardfactory's answer is what you need.如果您想强制在调用
bar
时提供myFlag
是Foo
class,那么@leonardfactory 的答案就是您所需要的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.