Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript: Describe Object of Objects

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.

like image 298
Dustin Michels Avatar asked Dec 11 '18 22:12

Dustin Michels


People also ask

How do you define object of objects type in TypeScript?

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.

How do you define an array of objects in TypeScript?

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!

What is type {} in TypeScript?

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.

How do you pass an object as a parameter in TypeScript?

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.


2 Answers

you can simply make the key dynamic:

interface IStudentRecord {
   [key: string]: Student
}
like image 124
messerbill Avatar answered Sep 22 '22 08:09

messerbill


Use the built-in Record type:

type StudentsById = Record<Student['id'], Student>;
like image 37
Karol Majewski Avatar answered Sep 24 '22 08:09

Karol Majewski