网站搜索

javascript - 如何在 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 
    }
}

我评论了,我应该从 IDE 得到错误信息,但我没有得到。这种情况的正确方法是什么?

我有很多群组,还有5种类型的群组文件。这些是常量,硬编码在应用程序中。

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

这是一个演示

答案#1

你目前是类型转换,而你想要断言类型,这可以通过一个小助手来完成:

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

可用作:

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

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

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

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