'Using enums for keys in an object in order to reuse in mutation
What is the best way to store the keys of an object and their types so that the keys can be used as a value and not just a type? I would like to check an attribute string against the enum within a mutation function so the type of the value can be checked against the expected type.
When using enums to declare keys and then name the enum's types, TS doesn't seems to be checking if a value is within an enum or not correctly.
export enum CellKeyStrings {
CHARACTER = "character",
PATH_TO_BOARD = "pathToBoardId"
}
export enum CellKeyBooleans {
IS_PASSABLE = "isPassable"
}
export enum CellKeyReadOnly {
ID = "id"
}
type PartialRecord<K extends string, T> = {
[P in K]?: T;
};
type ReadOnlyRecord<K extends string, T> = {
readonly [P in K]: T;
};
type CellStringProperties = PartialRecord<CellKeyStrings, string>;
type CellBooleanProperties = PartialRecord<CellKeyBooleans, boolean>;
type CellReadOnlyProperties = ReadOnlyRecord<CellKeyReadOnly, string>;
export interface Cell
extends CellStringProperties,
CellBooleanProperties,
CellReadOnlyProperties {}
interface MutationFunctionProps {
cellId: string;
attribute: keyof Cell;
value: string | boolean;
}
const cells: Cell[] = [{ id: "A-1" }];
const mutationFunction = ({
cellId,
attribute,
value
}: MutationFunctionProps) => {
const selectedCell = cells.find(({ id }) => id === cellId);
if (!selectedCell) {
throw Error("cannot find cell");
}
if (
Object.keys(CellKeyBooleans).includes(attribute) &&
!Object.keys(CellKeyReadOnly).includes(attribute)
) {
if (typeof value !== "boolean") {
throw Error("incorrect value type for attribute");
}
selectedCell[attribute] = value;
}
};
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
