typescript - 打字稿:使用特定对象作为函数 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 }) {}
~~~
解决方案
问题是你说myFlag
must 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
调用时提供bar
的Foo
类,那么@leonardfactory 的答案就是您所需要的。
推荐阅读
- cuda - cuda 11 内核无法运行
- python - 如何将列添加到 numpy recarry
- google-cloud-platform - 我们如何使用数据资源获取 GCP 存储桶名称
- sql - .NET CORE:Dapper 映射多对多查询
- java - Gson.fromJSON 返回 0 和 null
- git - 如何在 git update 上触发 ansible playbook?
- apache-spark - 需要将列的值映射到另一列作为火花数据框中的键值对
- graph - Spotfire - 在一个图上选择数据并从前一个选择中取消选择
- spring-boot - 如何从几个 yaml 规范生成 swagger-ui?
- lambda - Hazelcast Jet - 如何在 Jet 管道中使用非静态方法