Tautvydas Tautvydas - 3 months ago 9
Javascript Question

Typescript: How to define interface for dynamical object like this

Let's say I have function which takes this object as one of the arguments:

{
section: "main",
sectionColor: "#0072c6",
favIcon: "default",
libraries: {
value: "librariesFiles",
type: "jsIncludes"
},
components: {
value: "comoponentFiles",
type: "jsIncludes"
}
}


Here is interface I came up to define this property in function:

interface IgenerateFileArgumentObjectItem {
value: string;

type: string;
}

export interface IgenerateFileArgument {
[key: string]: (string | IgenerateFileArgumentObjectItem);
}


Shortly, I'm trying define object with dynamic number of properties which can be equal either to string value either to another object with two properties...

But compiler is complaining, and I think issue is in this line:
(string | IgenerateFileArgumentObjectItem)

Is there any obvious mistake or am I trying to do impossible thing?

I'm getting error here

And the error

Answer

I have created the following example, you can view it here in the TS playground. I was able to reconstruct you're issue. It seems that either one (or all) of the following librariesFiles, componentFiles, modellingContentStates, sharePointStates is of type string[].

interface IgenerateFileArgumentObjectItem {
    value: string;

    type: string;
}

export interface IgenerateFileArgument {
    [key: string]: (string | IgenerateFileArgumentObjectItem);
}

var p: string = 'uo'
var lol :string[] = ['no', 'po']; // Fix this to string type
var a: IgenerateFileArgument = {
    c: {
        value: p,
        type:'mo'
    },
    b:'lol',
    e: {
        value:'yo',
        type:'mo'
    },
    m: {  // you can remove this instead
        value:lol,
        type:'go'
    }
}