I'm trying to write a class that uses its generic type as the object to be destructured to enforce only those fields to be used.
Is it possible to use typescript to indicate that an object must be destructured, and work with its fields?
class A<T> {
doSomething ( { destructured object }: T) {
// work with destructured T...
}
}
For example, id like an object with this interface to be inserted in a database:
interface AnInterface { a: number; b: string; }
So I create this generic class
Class CRUDLService<T> {
create( { destructured object }: T ) {
// Insert object with the fields of T only, not any other
}
}
So I can create a generic service, for example:
const anInterfaceService = new CRUDLService<AnInterface>();
This way I could try to ensure that whenever anInterfaceService.create is called, only the right fields are being used.
The way I'm doing it right now doesn't take advantage of typescript, instead when you create these generic classes, you need to specify an array of strings that represent the fields being extracted from the object for the operation. ie:
const createFields = ['a', 'b'];
<T>- because once you destructure it you have individual variablesinterface IMinimumProperties { property1: string, [key: string]: any }. This way you can enforce some propertiesobj.aandobj.byou can shorten this toaandbbut it's just an alternative, not something code should rely on.