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;
}
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With