TypeScript空对象文字类型注释

时间:2015-11-13 20:35:23

标签: javascript types annotations typescript

在TypeScript中,如何在以下情况下注释对象文字的类型?

users for match generation createdcurrent number of matches: 0
[error] c.MatchDataController - here is the list: jnkj
[error] c.MatchDataController - here is the list: hbhjbjjnkjn
current number of matches: 0
current number of matches: 0
current number of matches: 0
current number of matches: 0
current number of matches: 0

对象// 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; }); 将初始化为空。我不知道稍后会向对象添加多少属性,我不知道它们的键的名称,但我知道它们的值将是字符串。有没有正确的方法来注释?我在文档和规范中都找不到任何相关内容。而且我不想从myObj中创建一个数组。请不要更改我的示例中的代码。我只是想知道如果有正确的类型注释是什么。

3 个答案:

答案 0 :(得分:3)

Here是关于如何键入空对象文字的说明。 但是,我认为该方法必须是可读代码与可扩展代码,在您的情况下,我发现您需要创建自己的属性/字典键,因此我将使用类似于以下内容的方法:

// 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}`;
}

希望这是有道理的。

答案 1 :(得分:-2)

对于要使用字符串访问并获取数字的对象,请使用以下命令:

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

示例:

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

对于要使用数字进行访问并获取字符串的对象,请使用此选项:

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

示例:

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

答案 2 :(得分:-4)

我认为你所需要的只是:

var myObj : String[] = [];
相关问题