打字稿 - 不能分配给学生类型

问题描述 投票:0回答:1

我在构造函数>> this.allStudents中有错误

class Students {
    public StudentsId: number;
    public StudentsName: string;
    public allStudents?: Students[];
    constructor() {
        this.allStudents = [
            { StudentsId: 100, StudentsName: 'Mahmoud'},
            { StudentsId: 101, StudentsName: 'Sami' },
            { StudentsId: 102, StudentsName: 'Osama' },
            { StudentsId: 103, StudentsName: 'Amer' },
            { StudentsId: 104, StudentsName: 'Ahmad' },
            { StudentsId: 105, StudentsName: 'Fadi' }
        ];
    }

    get getAllStudents() {
        return null;
    }
    getStudentById(_studentsId) {
        return this.allStudents.filter(x => x.StudentsId === _studentsId);
    }
    set addStudent(_student) {

    }


}

我不知道为什么会发生这种错误。我需要一些帮助来解决这个问题。

我如何在课程students中使用此界面?请检查界面IStudents如下:

interface IStudents {
    name: string,
    age: number,
    active:boolean
};
javascript typescript
1个回答
1
投票

我不明白为什么你需要一个Students的递归结构,所以用你感兴趣的属性定义一个Student并引用它。它可以是类,接口或类型。

下面的示例将StudentStudents列表分开,您可能希望更改名称以使其更明确。

interface Student {
    StudentsId: number;
    StudentsName: string;
}

class Students {
    public StudentsId: number;
    public StudentsName: string;
    public allStudents: Student[] = [];

    constructor() {
        this.allStudents = [
            { StudentsId: 100, StudentsName: 'Mahmoud'},
            { StudentsId: 101, StudentsName: 'Sami' },
            { StudentsId: 102, StudentsName: 'Osama' },
            { StudentsId: 103, StudentsName: 'Amer' },
            { StudentsId: 104, StudentsName: 'Ahmad' },
            { StudentsId: 105, StudentsName: 'Fadi' }
        ];
    }

    get getAllStudents() {
        return null;
    }

    getStudentById(_studentsId) {
        return this.allStudents.filter(x => x.StudentsId === _studentsId);
    }

    set addStudent(_student) {

    }
}

Hierarchy of Students

如果你真的需要一个学生层次结构,你可以这样做:

class Students {
    public subStudents: Students[] = [];

    constructor(public StudentsId: number, public StudentsName: string) {
        this.subStudents = [
            new Students(100, 'Mahmoud'),
            new Students(101, 'Sami'),
            new Students(102, 'Osama'),
            new Students(103, 'Amer'),
            new Students(104, 'Ahmad'),
            new Students(105, 'Fadi'),
        ];
    }

    get getAllStudents() {
        return null;
    }
    getStudentById(_studentsId) {
        return this.subStudents.filter(x => x.StudentsId === _studentsId);
    }
    set addStudent(_student) {

    }
}

Optionality of Array Types

我在两个代码示例中表达了我的观点,即空数组是不合需要的。您可以将其设置为非可选,并将其实例化为空数组,这样就无需在使用前对数组进行空值检查。

© www.soinside.com 2019 - 2024. All rights reserved.