Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typescript/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Typescript 如何定义类型,以便能够将具有通用字符串键的记录分配给自定义枚举键_Typescript - Fatal编程技术网

Typescript 如何定义类型,以便能够将具有通用字符串键的记录分配给自定义枚举键

Typescript 如何定义类型,以便能够将具有通用字符串键的记录分配给自定义枚举键,typescript,Typescript,我的应用程序接收已知标志(基本上是键值对象)的数据,但我只对这些标志的子集感兴趣。我想写一个类型,它不仅是像Record这样的记录,而且我希望每个标志都由enum标识。我是这样开始的: interface FlagsDataModel< T extends Record<string, FlagDataModel> = Record<string, FlagDataModel> > { flags?: T; } interface FlagD

我的应用程序接收已知标志(基本上是键值对象)的数据,但我只对这些标志的子集感兴趣。我想写一个类型,它不仅是像
Record
这样的记录,而且我希望每个标志都由
enum
标识。我是这样开始的:

interface FlagsDataModel<
    T extends Record<string, FlagDataModel> = Record<string, FlagDataModel>
> {
    flags?: T;
}

interface FlagDataModel<T = boolean> {
    value: T;
}
API可能会返回这样的数据,但我只对其中的子集感兴趣:

// mock
const genericFlagsData: FlagsDataModel = {
    flags: {
        'custom-foo': { value: true },
        'custom-bar': { value: true },
        'custom-foobar': { value: true },
        'custom-barfoo': { value: true }
    }
};
最后,我想将这些API
genericFlagsData
分配给我的
customFlagsData
,并使用
enum
值作为键访问数据:

const customFlagsData: CustomFlagsDataModel = genericFlagsData; // Error occurs 
console.log(customFlagsData[CustomNames.BAR]) // <-- should log { value: true }
const customFlagsData:CustomFlagsDataModel=genericFlagsData;//发生错误
console.log(customFlagsData[CustomNames.BAR])//
const customFlagsData: CustomFlagsDataModel = genericFlagsData; // Error occurs 
console.log(customFlagsData[CustomNames.BAR]) // <-- should log { value: true }
Type 'FlagsDataModel<Record<string, FlagDataModel<boolean>>>' is not assignable to type 'CustomFlagsDataModel'. Type 'Record<string, FlagDataModel<boolean>>' is missing the following properties from type '{ "custom-bar": FlagDataModel<boolean>; "custom-foo": FlagDataModel<boolean>; }': [CustomNames.BAR], [CustomNames.FOO]