'In flow, can you define an exact object type, using string types to define the keys
In flow, is it possible to define an exact object type, where the keys are also types?
In typescript you can accomplish this using strings, like...
export const userSettingsId = 'user-settings';
export type UserSettings = {
favourites: boolean,
};
export const groupSettingsId = 'group-settings';
export type GroupSettings = {
enabled: boolean,
};
export type Settings = {
[userSettingsId]: UserSettings,
[groupSettingsId]: GroupSettings,
};
const valid: Settings = {
'user-settings': { favourites: true },
'group-settings': { enabled: true }
}
const invalid1: Settings = {
'user-settings': { favourites: true },
'group-settings': { enabled: true },
'friend-settings': { enabled: true }
}
const invalid2: Settings = {
'user-settings': { favourites: true },
'group-settings': { enabled: true, burritos: true },
}
You cannot use strings as types in flow, but you also do not seem to be able to use string literal types. Flow seems to expect types for keys to be an indexer which doesn't then support this.
This does not work for example...
export type UserSettingsId = 'user-settings';
export const userSettingsId: UserSettingsId = 'user-settings';
export type UserSettings = {|
favourites: boolean,
|};
export type GroupSettingsId = 'group-settings';
export const groupSettingsId: GroupSettingsId = 'group-settings';
export type GroupSettings = {|
enabled: boolean,
|};
export type Settings = {|
[UserSettingsId]: UserSettings,
[GroupSettingsId]: GroupSettings,
|};
The reason I want to do this, is so I can use the key on its own and ensure it is in sync with the object for when you lookup the key. Does anyone know if there is any solution to this in flow?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
