Viraj Shah
Viraj Shah

Reputation: 792

TypeScript Interface not working as I expected

So right now, I'm trying to make a small modular web application. I am using typescript, which I am quite new to.

In my code, I:

Here is my code:

interface ProgramInfo {
    path:string;
    name:string;
    pkgname:string[];
    start?:string[];
    cli?:string[];
}

let program = {
    ProgramList: ProgramInfo[]
};

program.ProgramList = [
    {
        path: "/default_programs/WOSPMan",
        name: "WOSPMan (WebOS Package Manager)",
        pkgname: ["com", "webos", "wospman"],
        start: ["wospman", "wospm"],
        cli: ["wospman"]
    }
];

My IDE (JetBrains WebStorm), keeps giving me TypeScript Compile errors:

although I clearly defined ProgramInfo on the first few lines.

Upvotes: 0

Views: 3049

Answers (3)

Nitzan Tomer
Nitzan Tomer

Reputation: 164307

It should be:

interface Program {
    ProgramList: ProgramInfo[]
}

let program: Program = {
    ProgramList: []
};

Upvotes: 1

Maxx
Maxx

Reputation: 1748

When you do:

let program = {
    ProgramList: ProgramInfo[]
};

You declare object program with property ProgramList. But you trying to assign array of interfaces to this property, it does not make sense. You can do like this:

let program: {ProgramList: ProgramInfo[]} = {
    ProgramList: []
};

Or like this:

interface Program {
    ProgramList: ProgramInfo[];
}

let program: Program = {
    ProgramList: []
};

Upvotes: 2

Luka Jacobowitz
Luka Jacobowitz

Reputation: 23532

let program = {
    ProgramList: ProgramInfo[]
};

You're using an object literal here! Which means the double colon : doesn't mean ProgramList is of type ProgramInfo[], but instead means assign program.ProgramList to the variable ProgramInfo, which of course doesn't exist.

What you should do instead is assign an empty Array to the ProgramList field.

let program = {
    ProgramList: []
};

If you're looking for more typesafety you could of course add an interface that describes your program object.

interface Program{
    ProgramList: ProgramInfo[];
}

Upvotes: 1

Related Questions