Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript interface generic property names

Say we have two variables

const x='property1' const y='property2'

and we have function

function foo<key extends keyof MapInterface>(name: key, props: (MapInterface[key]))

This interface should look like

interface MapInterface{
'property1':any;
'property2':any;
}

Is it possible to have the interface be generically created like by calling the variables x,y

interface MapInterface{
x:any; //return 'property1':any;
y:any; //return 'property2':any;
}
like image 467
Abdullah El-Kindy Avatar asked May 17 '26 05:05

Abdullah El-Kindy


1 Answers

Yes, you can do this as of TypeScript 2.7, with constant-named properties, introduced in pull request Microsoft/TypeScript#15473. The only thing you are missing is that you need to use computed property syntax (the property name must be encased in brackets):

const x = 'property1'
const y = 'property2';

interface MapInterface {
  [x]: any;
  [y]: any;
} 

declare const mapInt: MapInterface;
mapInt[x]; // works      
mapInt[y]; // works
mapInt.property1; // also works
mapInt.property2; // also works

Hope that helps. Good luck!

like image 70
jcalz Avatar answered May 18 '26 22:05

jcalz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!