Reputation: 1043
I am trying to type the following
interface IStudentType {
[key: `${Students}`]: IStudent | IStudentMaths| IStudentPhysics
}
The issue I get is TS1268: An index signature parameter type must be 'string', 'number', 'symbol', or a template literal type.
Fair enough so I try
type StudentCategories = 'Mature' | 'Graduate' | 'Fresher' // these are the keys in the data
interface IStudentType {
[key: `${StudentCategories}`]: IStudent | IStudentMaths| IStudentPhysics
}
TS1337: An index signature parameter type cannot be a literal type or generic type. Consider using a mapped object type instead.
Any ideas how to fix this?
Upvotes: 1
Views: 795
Reputation: 33051
If you have a union of keys, you should use Record
type StudentCategories = 'Mature' | 'Graduate' | 'Fresher' // these are the keys in the data
type IStudent = {
tag: 'IStudent '
}
type IStudentMaths = {
tag: 'IStudentMaths'
}
type IStudentPhysics = {
tag: 'IStudentPhysics'
}
type StudentType = Record<StudentCategories, IStudent | IStudentMaths | IStudentPhysics>
It is possible to use Symbol and Template String Pattern Index Signatures and PR but then you need to add a prefix:
interface StudentType {
[prop: `${string}-${StudentCategories}`]: IStudent | IStudentMaths | IStudentPhysics
}
Upvotes: 1