我有一个非常大的REST,我从一个角度的应用程序中消费,我想迁移到代码生成。它在OpenAPI客户端生成器的另一个项目中运行良好。
我不想让我的生活变得比必要更困难,因此我必须扩展生成的接口,以便响应对象与现有代码兼容。不幸的是,在类型记录中不可能为接口编写扩展方法。所以我在考虑一个解决办法。
这个想法是为我的模型创建一个简单的包装类。
让我说,我有以下答复:
interface FooResponse {
test: number;
}我会为此创建一个模型:
class Model {
constructor(source: object) {
for (var property in source) {
if (source.hasOwnProperty(property)) {
(this as any)[property] = source[property];
}
}
Object.freeze(this);
}
}
// ERROR: Class 'FooModel' incorrectly implements interface 'FooResponse'.
// Property 'test' is missing in type 'FooModel' but required in type 'FooResponse'.
class FooModel extends Model implements FooResponse {
constructor(source: object) {
super(source);
}
// ERROR: Property 'test' does not exist on type 'FooModel'.
public get squareTest() {
return this.test * this.test;
}
}如代码示例中所述,我得到了两个错误。
Class 'FooModel' incorrectly implements interface 'FooResponse'. Property 'test' is missing in type 'FooModel' but required in type 'FooResponse'.Property 'test' does not exist on type 'FooModel'. (2 times)所以我的问题是:
我可以告诉编译器,我的接口实际上是implemented?
发布于 2021-09-01 20:35:33
类型记录中的类定义还会创建同名的接口。你可以像下面这样扩充它。不确定到底是怎么回事,但它告诉类型记录该属性确实存在。
interface FooModel extends FooResponse {}
class FooModel extends Model {
...
public get squareTest() {
return this.test * this.test;
}
}发布于 2021-09-01 20:25:04
像这样的东西对你有用吗?
interface FooResponse {
test: number;
}
interface FooResponseEnhanced extends FooResponse {}
class FooResponseEnhanced {
constructor (foo: FooResponse) {
Object.assign(this, foo, {})
}
public get squareTest() {
return this.test * this.test;
}
}
console.log(new FooResponseEnhanced({test: 2}).squareTest);是的,您需要完成额外的步骤,将需要用特殊函数扩展的响应包装起来,所以这并不完美。
发布于 2021-09-01 23:49:18
如果要将接口更改为抽象类,则可以这样做。
// In this abstract class you can define as many properties as you need
abstract class FooResponse {
test!: number;
}
// For simplification I would directly use Object.assign without
// needing a second base-class to inherit from
class FooModel extends FooResponse {
constructor(source: object) {
super();
Object.assign(this, source);
}
public get squareTest() {
return this.test * this.test;
}
}
// Usage example
const fm = new FooModel({test: 6});
const result = fm.squareTest;
console.log(result);https://stackoverflow.com/questions/69019840
复制相似问题