I have several interfaces which always have a field
member in common which itself always has one body
field but can have also other fields.
I want to implement a generic abstract class with T
which represents this subsections of all interfaces so that the abstract class can implement function which can access fields.body
of this type.
Here is an example:
interface SomeInterface{
title:string;
fields: {
title: { "en-US": string };
body: { "en-US": any };
some:{inter:string};
different:string;
}
}
interface SimilarbutNotSameInterface{
description:string;
fields: {
title: { "en-US": string };
body: { "en-US": any };
similar:number;
not:string;
}
}
abstract class Manipulator<T>{
abstract allInterfaces:T;
Manipulator(): T {
SomeOtherfunction(this.allInterfaces.fields.body["en-US"]);
return this.allInterfaces;
}
}
Is this possible with Typescript?
CodePudding user response:
I would go for:
interface AbstractStructure {
fields: Array<{
body: unknown;
}>
}
interface Structure1 extends AbstractStructure {
fields: Array<{
body: unknown;
property1: string;
}>
}
interface Structure2 extends AbstractStructure {
fields: Array<{
body: unknown;
property2: string;
}>
}
abstract class AbstractManipulator<T extends AbstractStructure> {
abstract structures: T[];
manipulate(): T[] {
// We can safely access this property since it is present on AbstractStructure type
console.log(this.structures[0].fields[0].body);
return this.structures;
}
}
This way AbstractManipulator
will work with interface as long it extends AbstractStructure
, which defines your desired fields.