简体   繁体   English

TypeScript空对象文字类型注释

[英]TypeScript Empty Object Literal Type Annotation

In TypeScript, how do I annotate the type of an object literal in the following situation? 在TypeScript中,如何在以下情况下注释对象文字的类型?

// Whats the type annotation of this object?
var myObj = {};
// Consider that `myArr` is dynamically filled with data
var myArr : string[] = [ 'foo', 'bar', 'baz' /* and many more items */ ];

myArr.forEach(function ( key: string ) {
    // I just know that `key` is a string
    // in this case but I don't know whether
    // it is empty or whats exactly in it
    // as `myArr` is the result of a DB query
    myObj[ key ] = 'Hello ' + key;
});

The object myObj will be initialized empty. 对象myObj将初始化为空。 I don't know how many properties will be added to the object later and I don't know the name of their keys, but what I know is that their values will be strings. 我不知道稍后会向对象添加多少属性,我不知道它们的键的名称,但我知道它们的值将是字符串。 Is there a proper way to annotate that? 有没有正确的方法来注释? I can't find anything about that neither in the docs nor in the spec. 我在文档和规范中都找不到任何相关内容。 And I don't want to make an Array out of myObj . 而且我不想用myObj制作一个数组。 Please do not change the code from my example. 请不要更改我的示例中的代码。 I just want to know what the correct type annotation is if there is one. 我只是想知道如果有一个正确的类型注释是什么。

Here is an explanation about how to type the Empty Object Literal. 以下是有关如何键入空对象文字的说明。 However, I believe that the approach must be readable code vs. extensible code, in your case I see that you need to create your own properties / dictionary keys, so I'd use something similar to the following: 但是,我认为该方法必须是可读代码与可扩展代码,在您的情况下,我发现您需要创建自己的属性/字典键,因此我将使用类似于以下内容:

// Declare a custom interface to type the object
interface CustomObject {
   [index: string]: string
}

// Implementation
let myObj: CustomObject = {};

for (let key of myArr) {
    myObj[key] = `Hello ${key}`;
}

Hope this makes sense. 希望这是有道理的。

For an object that you want to access with strings and get numbers use this: 对于要使用字符串访问并获取数字的对象,请使用以下命令:

interface ArrayOfNumbers {
    [index: string]: length:number;
    length:number;
}

example: 例:

var x : ArrayOfNumbers = [];
x['one'] = 1; // ok
x['two'] = '2' // fail
x[22] = 22 // fail

For an object that you want to access with numbers and get strings use this: 对于要使用数字访问并获取字符串的对象,请使用以下命令:

interface ArrayOfStrings {
    [index: number]: string;
    length:number;
}

example: 例:

var x : ArrayOfStrings = [];
x[1] = 'one'; // ok
x['two'] = '2' // fail
x[22] = 22 // fail

我认为你所需要的只是:

var myObj : String[] = [];

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

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