1

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?

3
  • it's hard to understand the context here, for what you're trying to accomplish. anyways, you cannot use a runtime value like ${StudentCategories} in your key index type. Commented Feb 9, 2022 at 12:41
  • if you can provide more context for what you're trying to model, with the students information here, surely we can help point towards an elegant solution Commented Feb 9, 2022 at 12:41
  • You should use Record for this. Example: type StudentType = Record<StudentCategories, IStudent | IStudentMaths | IStudentPhysics> Commented Feb 9, 2022 at 12:47

1 Answer 1

1

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>

Playground

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
} 
Sign up to request clarification or add additional context in comments.

1 Comment

Where do you intend the [Record][1] link to go?

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.