简体   繁体   中英

How to define expected properties type to a dynamic object on typescript

I making a simple object validator. In my contructor function for my class the first property will be the schema validation and the second property the object to validate. For the first property anyone know a way to define the structure like this?

{
 prop1: { type: "string", message: "some message" },
 prop2: { type: "string", message: "some message" },
 prop3: { type: "string", message: "some message" },
 prop4: { type: "string", message: "some message" },
 prop5: { type: "string", message: "some message" },
 ....
}

The only thing a not getting here is how to create a dynamic object with a different names for the properties and make sure all of then will be a property with the type: string and message: string as properties. If don't have any form to do this, I have a way to guarantee all the properties have the structure?

Added an annotation and an example:

const example: {
  [index: string]: { type: string, message: string }
} = {
  prop1: { type: "string", message: "some message" },
  prop2: { type: "string", message: "some message" },
  prop3: { type: "string", message: "some message" },
  prop4: { type: "string", message: "some message" },
  prop5: { type: "string", message: "some message" },
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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