3

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;
}
3

1 Answer 1

2

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!

Sign up to request clarification or add additional context in comments.

2 Comments

The problem is x and y are being imported from a separate class, thus the values will be accessible to the interface on runtime and not compile time. So it, unfortunately, rejects this approach.
You should be able to access them in a separate class at compile time, but of course I don't know your setup... and you should edit your question with relevant information if you want a more targeted answer; the answer above does apply to your question as it is currently stated.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.