简体   繁体   English

Typescript 强制 object 解构

[英]Typescript enforce object destructuring

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.我正在尝试编写一个 class ,它使用其泛型类型作为 object 进行解构以仅强制使用这些字段。

Is it possible to use typescript to indicate that an object must be destructured, and work with its fields?是否可以使用 typescript 来指示必须解构 object 并使用其字段?

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:例如,像 object 这样的 id 具有要插入数据库的接口:

interface AnInterface { a: number; b: string; }

So I create this generic class所以我创建了这个通用的 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.这样我可以尝试确保每当调用 anInterfaceService.create 时,只使用正确的字段。

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.我现在这样做的方式并没有利用 typescript,而是在创建这些泛型类时,需要指定一个字符串数组,这些字符串表示从 object 中提取的用于操作的字段。 ie: IE:

const createFields = ['a', 'b']; 

You can ofcourse do that but what is T here, T is just a type without any property, so what will you destructure here.你当然可以这样做,但这里的T是什么,T 只是一个没有任何属性的类型,所以你将在这里解构什么。 You can define T as a variant of some type and use the object destructuring,您可以将T定义为某种类型的变体并使用 object 解构,

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.顺便说一句,如果您尝试从问题中解构您的T ,它确实有效。 It is simply empty object, I dont see any use case here.它只是空的 object,我在这里看不到任何用例。

So, this is perfectly valid syntax as well,所以,这也是完全有效的语法,

class A<T> {
  doSomething({}: T) {

  }
}

I don't think its possible to do this.我认为不可能做到这一点。 Types will have to be explicitly defined for each case.必须为每种情况明确定义类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM