Reputation: 12025
Why this defination of type is not allowed in TypeScript?
type profileType = 'TEACHER' | 'PRINCIPAL';
interface FormList {
[ key: profileType ] : IForm[];
}
let forms: FormList;
forms = {
'TEACHER' : [{ id: 1, name: "o" }, { id: 1, name: "b" }]
}
It invokes an error in line: [ key: profileType ] : IForm[];
.
Upvotes: 0
Views: 81
Reputation: 38046
You can map string literals from union into new type. This is called mapped type in typescript:
type IForm = {};
type ProfileType = 'TEACHER' | 'PRINCIPAL';
type FormList = { [P in ProfileType]: IForm[] };
let forms: FormList;
forms = {
'TEACHER': [{ id: 1, name: "o" }, { id: 1, name: "b" }],
'PRINCIPAL': [{ id: 1, name: "o" }, { id: 1, name: "b" }]
}
Upvotes: 1