Company logo
  • Empleos
  • Bootcamp
  • Acerca de nosotros
  • Para profesionales
    • Inicio
    • Empleos
    • Cursos y retos
    • Preguntas
    • Profesores
    • Bootcamp
  • Para empresas
    • Inicio
    • Nuestro proceso
    • Planes
    • Pruebas
    • Nómina
    • Blog
    • Comercial
    • Calculadora

0

70
Vistas
How to refer a interface that's used before it was defined?

I am defining TypeScript interfaces and landed in a situation where I need to define circular interface.

Eg. ISchool have IStudent and IStudent have ISchool, the problem is interface ISchool {} has IStudent which is used before it's defined. Also, I can't define interface IStudent before because IStudent has ISchool. How can handle this situation?

interface ISchool {
  id: string;
  name: string;
  students: IStudent[];
}

interface IStudent {
  id: string;
  name: string;
  school: ISchool;
}
7 months ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Better not to have circular dependencies in general. If you create a school with students the students contain a school which also contains students which also contains a school etc. That's why I reccomend you to rewrite your code so your IStudent interface references the schools with its id.

export interface ISchool {
    id: string;
    name: string;
    students: IStudent[];
  }
  
export interface IStudent {
    id: string;
    name: string;
    school: string;
}

Now you can pass the id of the school to the IStudent so your IStudent interface is still linked with your ISchool interface.

Or you could disable the eslint rule by adding this to your .eslintrc.json. Because after all its jsut a lint error and javascript allows almost everything.

"no-use-before-define": "off"
7 months ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos