Home > Software design >  Typescript - create interface from list of property names
Typescript - create interface from list of property names

Time:03-25

I want to be able to list all the properties in an interface at runtime but this doesn't look to be possible. So can I create an interface with a list of string property names?

Tried this but it doesn't work

interface MyInterface {
   prop1: string;
   propsList: MyProps;
}

type MyProps = "my_prop_1" | "my_prop_2"; //these types should be string


function addProps(){
   const myInterface: MyInterface = {
     prop1: "hello",
     propsList: {
       my_prop_1: "world",
       my_prop_2: "hello world"
     }
   }
}

Trying to use the interface results in

Type {my_prop_1: string, my_prop_2: string} is not assignable to type 'MyProps'

I then want to be able to use MyProps later as a list of strings to check the properties in another list.

Is this possible?

CodePudding user response:

Use an array of properties so you can use at runtime:

const myProps = ["my_prop_1", "my_prop_2"] as const;

Then you can get your old type MyProps like this:

type MyProps = (typeof myProps)[number];

And finally for your interface use a mapped type:

interface MyInterface {
   prop1: string;
   propsList: {
       [K in MyProps]: string;
   };
}
  • Related