Reputation: 598
I want to create an object what contain groups and the groups have files. The selectable files has an interface, and I want to get error if a group dont contain its files.
export interface Group_A_Files {
'movie': string
'image': string
'other': string
}
export interface Group_B_Files {
'image': string
}
export const groups = {
'groupA' : {
'someField': 'some value',
'files': <Group_A_Files> {
'movie': '',
'image': '',
} // I want to get an error from the IDE, because other is required in Group_A_Files, but not set by me
},
'groupB' : {
'someField': 'some value',
'files': <Group_B_Files>{
'image': '',
'bla': ''
} // I want to get an error from the IDE, because bla is not defined in Group_B_Files
}
}
I commented, where I should to get error message from the IDE, but I dont get. What is the right way for this?
I have a lot of groups, and 5 type of group file. These are constants, and hard coded into the app,
I dont want to define the hole groups in interface and then declare it too, just for get the error messages from the IDE, I would like to define the type when I set it.
Here is a demo
Upvotes: 2
Views: 2671
Reputation: 138447
You currently typecast, instead you want to assert types, which can be done with a small helper:
function <T> assert(el: T) { return el; }
Usable as:
'groupB' : {
'someField': 'some value',
'files': assert<Group_B_Files>({
'image': '',
'bla': ''
}),
}
Otherwise you could type the whole object:
interface IGroups {
groupA: {
someField: string;
files: Group_A_Files;
}
};
export const groups: IGroups = {
'groupA' : {
'someField': 'some value',
'files': <Group_A_Files> {
'movie': '',
'image': '',
}
},
};
Upvotes: 5