17

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.

2 Answers 2

29

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 
Sign up to request clarification or add additional context in comments.

1 Comment

Could you use a Record<string, Stats> as opposed to the Groups Interface?
21

Simpler way

You can use {[key:string]:string} as a type for any object with string values and string keys.

type strObj = {[key:string]:string}

const sample:strObj = {
    one:"text1",
    two:"text2"
}



For nested Object

And if it is a nested object, you can nest the type in place of the second string at the end.

{[key:string]: string} ==> {[key:string]: {[key:string]:string}}

Hence,

type strObj = {[key:string]:{[key:string]:string}}
const sample:strObj = {
    one:{
        sub:"text1"
    },
    two:{
        sub:"text2"
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.