Raisen
Raisen

Reputation: 4495

Defining an interface for an array in Typescript

I'm not yet familiar with Typescript, and I'm having troubles to define a simple array.

My goal is to have an array where the key is a string and its values are of types Sound.

I have defined an interface like that:

interface SoundsArrayType {
    [key: string]: Sound;
}

Then:

class SoundManager {
    private sounds: SoundsArrayType;

    constructor() {
      // error: Type 'undefined[]' is not assignable to type 'SoundsArrayType'.
      if(!this.sounds) this.sounds = [];
    }

    pauseAll() {
        for(let sound of this.sounds) {
            // error: Type 'SoundsArrayType' must have a '[Symbol.iterator]()' method that returns an iterator.
            sound.pause();
        }
    }
}

I'm not sure how to fix these errors. I read the Interfaces page from the Typescript site but I'm still stuck.

Upvotes: 2

Views: 662

Answers (2)

Adrian Brand
Adrian Brand

Reputation: 21658

interface Sounds { // It is not an array
    [key: string]: Sound;
}

Then:

class SoundManager {
    private sounds: Sounds = {}; // Just assign an empty object to it

    constructor() { }

    pauseAll() {
        for(let key of this.sounds.keys) {
            this.sounds[key].pause();
        }
    }
}

Upvotes: 0

Shaun Luttin
Shaun Luttin

Reputation: 141732

My goal is to have an array where the key is a string and its values are of types Sound.

This might be a good use for the the Map type.

Here it is in TypeScript.

type Sound = {
    name: string;
};

const myMap = new Map<string, Sound>();
myMap.set('dog', { name: 'woof' });
myMap.set('cat', { name: 'meow' });
myMap.set('fox', { name: 'what does the fox say?!?!' });

Here it is in JavaScript without the type checking.

const myMap = new Map();

myMap.set('dog', { name: 'woof' });
myMap.set('cat', { name: 'meow' });
myMap.set('fox', { name: 'what does the fox say?!?!' });

for (let value of myMap.values()) { 
    console.log(value.name);
}

for (let key of myMap.keys()) { 
    console.log(key);
}

for (let [key, value] of myMap) { 
    console.log(key + ':' + value.name);
}

Upvotes: 2

Related Questions