Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

typescript type object with string keys and content defined by interface

Tags:

typescript

my data has this structure:

groups = {
    someGroupName: {
        total: 30,
        count: 3,
        average: 10
    },
    someOtherGroupName: {
        total: 60,
        count: 3,
        average: 20
    }
}

I can write an interface for the nested part:

interface Stats {
    total: number,
    count: number,
    average: number
}

but how can I set a type for groups as a whole? I do not know what groups are coming in. I just know that it will be a groupname as the key and the stats object as the value.

like image 777
Chris Avatar asked Jun 21 '18 16:06

Chris


1 Answers

You can use an index signature to tell typescript that the object is indexable by any string but all values in the object are of a certain type:

interface Stats {
    total: number,
    count: number,
    average: number
}

interface Groups {
    [name: string] : Stats
}

let groups: Groups = {
    someGroupName: {
        total: 30,
        count: 3,
        average: 10
    },
    someOtherGroupName: {
        total: 60,
        count: 3,
        average: 20
    }
}

let someGroupName = groups['someGroupName'] //someGroup is Stats
groups['someGroupName'] = 0 // invalid 0 is not of type Stats 
like image 102
Titian Cernicova-Dragomir Avatar answered Sep 21 '22 22:09

Titian Cernicova-Dragomir