在打字稿中使用字符串作为索引

Using a string as an index in typescript

我正在尝试输入以下内容

    interface IStudentType {
      [key: `${Students}`]: IStudent | IStudentMaths| IStudentPhysics
     }

我遇到的问题是TS1268:索引签名参数类型必须是'string'、'number'、'symbol'或模板文字类型。

很公平,所以我试试

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.

有什么解决办法吗?

如果你有一个联合键,你应该使用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

可以使用Symbol and Template String Pattern Index Signatures and PR但是你需要添加一个前缀:


interface StudentType {
    [prop: `${string}-${StudentCategories}`]: IStudent | IStudentMaths | IStudentPhysics
}