简体   繁体   中英

How to declare nested object types safely in typescript

I want to create an object what contain groups and the groups have files. The selectable files has an interface, and I want to get error if a group dont contain its files.

export interface Group_A_Files {
    'movie': string
    'image': string
    'other': string
}

export interface Group_B_Files {
    'image': string
}

export const groups = {
    'groupA'  : {
        'someField': 'some value',
        'files': <Group_A_Files> {
            'movie': '',
            'image': '',
        } // I want to get an error from the IDE, because other is required in Group_A_Files, but not set by me
    },
    'groupB'  : {
        'someField': 'some value',
        'files': <Group_B_Files>{
            'image': '',
            'bla':  ''
        } // I want to get an error from the IDE, because bla is not defined in Group_B_Files 
    }
}

I commented, where I should to get error message from the IDE, but I dont get. What is the right way for this?

I have a lot of groups, and 5 type of group file. These are constants, and hard coded into the app,

I dont want to define the hole groups in interface and then declare it too, just for get the error messages from the IDE, I would like to define the type when I set it.

Here is a demo

You currently typecast, instead you want to assert types, which can be done with a small helper:

  function <T> assert(el: T) { return el; }

Usable as:

'groupB'  : {
    'someField': 'some value',
    'files': assert<Group_B_Files>({
        'image': '',
        'bla':  ''
    }),
}

Otherwise you could type the whole object:

interface IGroups {
  groupA: {
    someField: string;
    files: Group_A_Files;
 }
};

export const groups: IGroups = {
    'groupA'  : {
        'someField': 'some value',
        'files': <Group_A_Files> {
            'movie': '',
            'image': '',
         }
    },
};

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM