如何在打字稿中安全地声明嵌套对象类型

Two*_*ois 2 javascript node.js typescript

我想创建一个包含组的对象,并且组有文件。可选择的文件有一个界面,如果一个组不包含其文件,我想得到错误。

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 
    }
}
Run Code Online (Sandbox Code Playgroud)

我评论说,我应该在哪里从 IDE 获取错误消息,但我没有得到。正确的方法是什么?

我有很多组,以及 5 种类型的组文件。这些是常量,并硬编码到应用程序中,

我不想在接口中定义孔组然后再声明它,只是为了从IDE获取错误消息,我想在设置它时定义类型。

这是一个演示

Jon*_*lms 5

您当前需要进行类型转换,而不是想要断言类型,这可以使用一个小助手来完成:

  function <T> assert(el: T) { return el; }
Run Code Online (Sandbox Code Playgroud)

可用作:

'groupB'  : {
    'someField': 'some value',
    'files': assert<Group_B_Files>({
        'image': '',
        'bla':  ''
    }),
}
Run Code Online (Sandbox Code Playgroud)

否则你可以输入整个对象:

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

export const groups: IGroups = {
    'groupA'  : {
        'someField': 'some value',
        'files': <Group_A_Files> {
            'movie': '',
            'image': '',
         }
    },
};
Run Code Online (Sandbox Code Playgroud)