In TypeScript, how do I annotate the type of an object literal in the following situation?
// 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. 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
. 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[] = [];
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.