假设我有两个类,我希望它们在它们之间共享实用程序功能。该实用程序类访问作为对象类型的Map的属性。映射中存储的对象类型对于每个类都是不同的。该函数被称为与调用该函数的类的实例绑定的对象,并作为参数将其应添加到映射中的对象作为参数传递。过度简化的版本可能看起来像这样。
interface fooItem {
name: string
}
interface barItem {
name: string
compact: boolean
}
function setItems(this: Foo | Bar,item: fooItem | barItem) {
// Error here on 'item' arg
this.items.set(item.name,item);
}
class Foo {
constructor() {
this.items = new Map();
}
items: Map<string,fooItem>;
setItems = setItems.bind(this);
}
class Bar {
constructor() {
this.items = new Map();
}
items: Map<string,barItem>;
setItems = setItems.bind(this);
}
Link to this code on typescript Playground
此代码引发编译器错误
Argument of type 'fooItem | barItem' is not assignable to parameter of type 'barItem'.
Property 'compact' is missing in type 'fooItem' but required in type 'barItem'.
目的是使对象只能与其关联的类一起使用,但是我知道编译器无法保证它们是配对的。
什么是正确的打字稿语法,如果编译器知道项为fooItem
,该选项将为Foo
,反之亦然?