In Typescript, why do I need to set a class property that is defined as read-only?

I have the following class definition:

class Department
{
    name: string;
    id: string;

    get prefix(): string
    {
        return  !isNaN(parseFloat(this.id)) ? "n" : "i" ;
    }
}

Elsewhere in my code, I try to use it as follows:

getDepartmentList(): Department[] {
    return [
        {
            "name": "Dept 1",
            "id": "1000"
        }
    ];
}

However, I get the following error:

Enter '{"name": string; "id": string; } 'is not assigned to the type "Department". The prefix of the property 'is absent in type' {"name": string; "id": string; } ".

I'm sure the real problem is a lack of understanding of Typescript, but can anyone explain why the compiler sees the getter function as a property and expects me to set a value on it?

+4
source share
1 answer

. , name, id prefix. , getDepartmentList, prefix, Department. , .

, , prefix -property -, , Department. , , typescript. , , , , .

:

class Department
{
    constructor(public name:string, public id:string){ }

    get prefix(): string
    {
        return  !isNaN(parseFloat(this.id)) ? "n" : "i" ;
    }
}

function getDepartmentList(): Department[]
{
    return [new Department("Dept 1", "1000")];
}

Department, .

typescript , .

:

class Department
{
    name: string;
    id:string;

    constructor(name:string, id:string){
        this.name = name;
        this.id = id;
    }

    get prefix(): string
    {
        return  !isNaN(parseFloat(this.id)) ? "n" : "i" ;
    }
}
+4

Source: https://habr.com/ru/post/1650083/


All Articles