Reputation: 32838
Here's my property where the interface is defined multiple times:
ExamStatusId = {
All: <IEnumElement>{
id: this.examStatusSelectId,
text: 'Exam Status: All',
val: 0
},
Current: <IEnumElement>{
id: this.examStatusSelectId,
text: 'Exam Status: Current',
val: 1
}
}
Here's the interface that I have:
interface IEnumElement {
elem: string;
text: string;
val: number
}
Is there any way that I can avoid having to specify the interface after every property of ExamStatusId?
Upvotes: 0
Views: 103
Reputation: 276323
Depends upon your purpose. If your purpose is to get the intellisense + type checking when accessing members of the Object as shown below:
And you want the intellisense + type checking when creating the individual members:
Then the solution you have is the best one I can think of.
Upvotes: 0
Reputation: 14577
Yes that is possible with an extra interface like the code below. The generic IIndexable interface makes it also easy to use on different places!
interface IEnumElement {
elem: string;
text: string;
val: number
}
interface IIndexable<T> {
[index: string]: T;
}
var ExamStatusId: IIndexable<IEnumElement> = {
All: {
elem: "",
text: 'Exam Status: All',
val: 0
},
Current: {
elem: "asdf",
text: 'Exam Status: Current',
val: 1
},
X: {} // this is now an error!
}
edit: The nice thing about using the interface is that you will get autocompletion too!
Upvotes: 1
Reputation: 251242
You haven't included the elem
property, so you need to do that (although this is tangential).
My recommendation is that you embrace the wonder of type inference, and do this:
interface IEnumElement {
elem: string;
text: string;
val: number
}
class Exam {
private examStatusSelectId: number;
ExamStatusId = {
All: {
id: this.examStatusSelectId,
elem: '',
text: 'Exam Status: All',
val: 0
},
Current: {
id: this.examStatusSelectId,
elem: '',
text: 'Exam Status: Current',
val: 1
}
}
}
// This function must be passed an IEnumElement
function example(element: IEnumElement) {
}
var exam = new Exam();
// The compiler knows this is good
example(exam.ExamStatusId.All);
If you didn't include the correct properties when you declared the ExamStatusId
property on your class, the compiler would correctly detect the problem and tell you about it, because it will compare the best common type in the ExamStatusId
with the IEnumElement
interface (so even if you only missed elem
off of one, you'd get the warning.
Upvotes: 1