简体   繁体   中英

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 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'
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM