Reputation: 328
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'];
Upvotes: 0
Views: 736
Reputation: 328
I don't think its possible to do this. Types will have to be explicitly defined for each case.
Upvotes: 0
Reputation: 21144
You can ofcourse do that but what is T
here, T is just a type without any property, so what will you destructure here. You can define T
as a variant of some type and use the object destructuring,
Here is a simple example,
interface SomeProps {
name: string;
}
class A<T extends SomeProps> {
doSomething({ name }: T) {
console.log(name);
}
}
By the way, it does work if you try to destructure your T
from the question. It is simply empty object, I dont see any use case here.
So, this is perfectly valid syntax as well,
class A<T> {
doSomething({}: T) {
}
}
Upvotes: 1