typescript - 在打字稿中初始化字典
问题描述
我想在 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"
}
}]
}
我怎么能这样做?
解决方案
你可以定义为
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'])
推荐阅读
- python - Discord.py 机器人,根据特定角色执行响应
- javascript - jQuery - 如何替换 keyup 上的输入值?
- c++ - C++:将数学函数及其导数分组到一个实体中
- python - Python Gurobi 设置目标函数
- html - How do I make a part of a div hide itself off screen?
- scala - 从 Redshift 读取到 Spark Dataframe(Spark-Redshift 模块)
- javascript - 我如何组合这些代码?(阅读更多,滚动到顶部阅读更少)
- php - PHP 中的 Password_verfiy 失败
- python - 将标记设置为随 y 轴缩放(有限制)
- vb.net - VB.NET 控制台应用程序等价于 Python Input()