Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to get the string representation of property names from a given typescript type

I am new to typescript so this question might be trivial.

Say I defined a type like

type MyType = {
  name: string,
  age: number,
}

and an object like

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

const o:MyType = {
  name:"John Doe",
  age:42
}

I could access the the name via o["name"].

Is it possible instead of using "name" something more safe like o[MyTypeProp.name] where MyTypeProp.name is derived from the actual type and contains every propertyname?

I was looking into MappedTypes and something similar to

type MyTypeProp = {
  [Property in keyof MyType]: Property;
};

which gave me not what I was hoping for.

My usecase is to make testing easier: I have a bunch of properties to test whether they are disabled writing this

expect(allDisabled(model, ["isTrackingPresent", "isDistributionPresent", ...]))

is more comfortable than testing each and every manually.

On top getting rid of those "magic strings" would be more comfortable.

>Solution :

It won’t be possible to generate some runtime constants using types, since all types will be gone in runtime. If the variables are correctly typed then there is no need for this kind of object.

It would be possible to generate a type out of the object that would show the structure of the type:

const factory = {
  name: {
   type: "string",
  },
  data: {
   type: "object", 
   fields: {
     age: {
       type: "number"
     }

   }
  }
  
} as const

Then have a type for converting "string", "number" to actual type:

type TypeMap = {
  string: string;
  number: number;
}

And using some mapped type you could recursively go through the factory and generate a type.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading