【发布时间】:2021-10-26 06:44:14
【问题描述】:
我的界面如下所示:
export interface Attribute {
name: string;
}
有了这个,我可以使用这个语法来创建一个Attribute:
const attr: Attribute = {
name: "foo"
};
我的问题是我不想使用类,因为它们笨拙且不够灵活,但我想继续使用上面的语法来创建对象,因为它非常简洁。我读过可以进行声明合并,所以我尝试这样做以向该接口添加一个新函数:
import { Attribute } from "./Attribute";
declare module "./Attribute" {
interface Attribute {
matches(other: Attribute): boolean;
}
}
Attribute.prototype.matches = function (other: Attribute): boolean {
return this.name === other.name;
};
这里的问题是没有prototype 可以扩充,因为接口在运行时不可用。如果我将Attribute 接口与一个类合并:
export class Attribute {}
export interface Attribute {
name: string;
}
有一个原型并且扩充编译但我仍然不能使用它:
import { Attribute } from "./Attribute";
import "./AttributeAugments";
const attr: Attribute = {
name: "foo"
};
// ^^^--- Property 'matches' is missing in type '{ id: number; name: string; }' but required in type 'Attribute'
console.log(attr);
有没有办法做到这一点?我的目标是能够做到attr.matches(other) 而不必做matches(attr, other)。这样我就可以像attr.a().b().c() 那样做函数链接,而不必做c(b(a(attr)))。
【问题讨论】:
-
你知道
attr的所有方法吗? -
你说类不够灵活,但看起来你只是想创建一个类,但隐含:)
标签: typescript