首页 > 解决方案 > 在打字稿中初始化字典

问题描述

我想在 typescript 中定义一个对象,它有一个名为property.

export interface Input {
    documents: Array<DocumentInput>;
}

export interface DocumentInput {
    properties?: {
            [key: string]: object;
        };
}

目前我这样做是为了定义属性。

const docProperties = {};
docProperties['name'] = 'ABC';
docProperties['description'] = 'PQR';

let request: Input = {
    documents :[
    {
        properties:docProperties
    }]
}

我想减少行并写这样的东西。

let request: Input = {
        documents :[
        {
            properties:
            {
               "name" : "ABC",
               "description" : "PQR"
            }
        }]
    }

我怎么能这样做?

标签: typescript

解决方案


你可以定义为

export interface Input {
  documents: any; // or object
}

export interface DocumentInput {
  properties?: any; // or object
}

并与

 let request: Input = {
            documents :[
            {
                properties:
                {
                   "name" : "ABC",
                   "description" : "PQR"
                }
            }]
        }

        console.log(request.documents[0].properties.name)
//or
        console.log(request.documents[0].properties['name'])

推荐阅读