Devcon Devcon - 4 months ago 68
TypeScript Question

Strongly typed typescript collections

I'm trying to use "collections" (what is this paradigm actually called?) in typescript and have them strongly typed. In javascript I would write something like this.

var array = [1,2,3,4];
var collection = {};

for(var x in array){
collection['item-'+x] = x;
}


I have an object, and I add/remove elements using this
collection[name]
syntax.

This is great because I don't need to care about index's.
Now in typescript when I make an array I can declare it and give it a type.

let array: string[] = [];


How would this equate to this collection syntax, for example I have a collection like this.

var days = {};

days[moment().day('monday')] = new dayType('Monday');
days[moment().day('tuesday')] = new dayType('Tuesday');


This works great, but if I access my collection
days[moment().day('monday')].Name
I don't know if that is actually my dayType class or just an object with a
Name
property on it. And same thing with the property name. I can add
days['July']: = false;
just fine, even though that doesn't make sense in the context of my object.

Is this just a paradigm that doesn't fit with typeScript?

What is this paradigm called?

Is there a better way of doing this?

Answer

The structure you're using here looks like a dictionary. Try the following:

var days : { [key: string]: dayType; } = {};

days[moment().day('monday')] = new dayType('Monday');

You can also use an interface for shorthand:

interface dayDictionary {
    [key: string]: dayType;
}

var days: dayDictionary = { };

see: TypeScript Objects as Dictionary types as in C#

Comments