繁体   English   中英

打字稿:如何为这样的动态对象定义接口

[英]Typescript: How to define interface for dynamical object like this

假设我有将这个对象作为参数之一的函数:

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

这是我在函数中定义此属性的接口:

interface IgenerateFileArgumentObjectItem {
    value: string;

    type: string;
}

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

不久,我正在尝试定义具有动态属性数量的对象,该属性可以等于字符串值,也可以等于具有两个属性的另一个对象...

但是编译器在抱怨,我认为问题出在这一行:(string | IgenerateFileArgumentObjectItem)

是否有任何明显的错误或我正在尝试做不可能的事情?

我在这里出错

和错误

我创建了以下示例,您可以在TS 操场上查看它。 我能够重建你的问题。 似乎以下库文件,componentFiles,modellingContentStates,sharePointStates中的一个(或全部)的类型为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'
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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