簡體   English   中英

TypeScript空對象文字類型注釋

[英]TypeScript Empty Object Literal Type Annotation

在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;
});

對象myObj將初始化為空。 我不知道稍后會向對象添加多少屬性,我不知道它們的鍵的名稱,但我知道它們的值將是字符串。 有沒有正確的方法來注釋? 我在文檔和規范中都找不到任何相關內容。 而且我不想用myObj制作一個數組。 請不要更改我的示例中的代碼。 我只是想知道如果有一個正確的類型注釋是什么。

以下是有關如何鍵入空對象文字的說明。 但是,我認為該方法必須是可讀代碼與可擴展代碼,在您的情況下,我發現您需要創建自己的屬性/字典鍵,因此我將使用類似於以下內容:

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

希望這是有道理的。

對於要使用字符串訪問並獲取數字的對象,請使用以下命令:

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

我認為你所需要的只是:

var myObj : String[] = [];

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM