Force Declaring Array with specific sort of complex types

Issue

I need a way to declare array with a specific order of types to force setting the required properties of each type as

list: (Teacher , School , Student , Teacher)[] = [
{id:1,fName:'jo1',sName:'jo11',position:'first teacher'},
{id:1,name:'oxford',location'us'},
{id:1,name:'rob',level:'junior'},
{id:2,name:'gen',level:'Senior'},
{id:2,fName:'jo1',sName:'jo11',name:'jo222',position:'second teacher'}
]
interface Teacher{
id;
fName;
sName;
position;
} 

interface School{
id;
name;
location;
}

interface Student {
id;
name;
level;
}

Solution

You need to define list as a tuple not an array type:

interface Teacher {
    id: number;
    fName: string;
    sName: string;
    position: string;
}

interface School {
    id: number;
    name: string;
    location: string;
}

interface Student {
    id: number;
    name: string;
    level: string;
}

let list: [Teacher, School, Student, Teacher] = [
    { id: 1, fName: 'jo1', sName: 'jo11', position: 'first teacher' },
    { id: 1, name: 'oxford', location'us'},
    { id: 1, name: 'rob', level: 'junior' },
    { id: 2, name: 'gen', level: 'Senior' },
    { id: 2, fName: 'jo1', sName: 'jo11', name: 'jo222', position: 'second teacher' }
]

TS playground

Answered By – Abdellah Hariti

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published