假设我有一个这样的界面:
interface Student {
firstName: string;
lastName: string;
year: number;
id: number;
}
如果我想传递这些对象的数组,我可以简单地将类型写为 Student[]
。
我使用的不是数组,而是一个对象,其中学生 ID 是键,学生是值,以便于查找。
let student1: Student;
let student2: Student;
let students = {001: student1, 002: student2 }
有什么方法可以将此数据结构描述为我传递给函数或从函数返回的类型吗?
我可以这样定义一个接口(interface):
interface StudentRecord {
id: number;
student: Student
}
但这仍然不是我想要的类型。我需要指示我有一个充满对象的对象,它看起来像这样,同样 Student[]
指示我有一个充满对象的数组,看起来像这样。
最佳答案
您可以简单地使 key 动态化:
interface IStudentRecord {
[key: string]: Student
}
关于javascript - TypeScript:描述对象的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53733322/