Say I have an interface like this:
interface Student {
firstName: string;
lastName: string;
year: number;
id: number;
}
If I wanted to pass around an array of these objects I could simply write the type as Student[]
.
Instead of an array, I'm using an object where student ids are keys and students are values, for easy look-ups.
let student1: Student;
let student2: Student;
let students = {001: student1, 002: student2 }
Is there any way to describe this data structure as the type I am passing into or returning from functions?
I can define an interface like this:
interface StudentRecord {
id: number;
student: Student
}
But that still isn't the type I want. I need to indicate I have an object full of objects that look like this, the same way Student[]
indicates I have an array full of objects that look like this.
To define an object of objects type in TypeScript, we can use index signatures with the type set to the type for the value object. const data: { [name: string]: DataModel } = { //... }; to create a data variable of type { [name: string]: DataModel } where DataModel is an object type.
To declare an array of objects in TypeScript, set the type of the variable to {}[] , e.g. const arr: { name: string; age: number }[] = [] . Once the type is set, the array can only contain objects that conform to the specified type, otherwise the type checker throws an error. Copied!
Summary. The TypeScript object type represents any value that is not a primitive value. The Object type, however, describes functionality that available on all objects. The empty type {} refers to an object that has no property on its own.
Inside the function we assign the parameters to properties in the object. To do this, we have to specify the this keyword, which refers to the calling object. The variables and parameters may have the same names. Anything we pass to the constructor as an argument, will be assigned to the property of the object.
you can simply make the key dynamic:
interface IStudentRecord {
[key: string]: Student
}
Use the built-in Record
type:
type StudentsById = Record<Student['id'], Student>;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With