I'm writing my application in TypeScript and I'm using Redux to keep track of my app state. My redux store state looks something like this:
interface AppState {
readonly grid : IGridSettings;
readonly selected : ISelectedSettings;
[key : string] : IGridSettings | ISelectedSettings;
}
interface IGridSettings {
readonly extents : number;
readonly isXY : boolean;
readonly isXZ : boolean;
readonly isYZ : boolean;
readonly spacing : number;
[key : string] : number | boolean;
}
interface ISelectedSettings {
readonly bodyColor : number;
readonly colorGlow : number;
readonly lineColor : number;
readonly selection : number[] | undefined;
[key : string] : number | number[] | undefined;
}
I created the following action to let me update the store however the setPropertyValue function is not ideal since it has no type safety!
//How to add type safety to this function?
const setPropertyValue = ( property : string[], value : any ) : SetPropertyValueAction => ( {
type: 'SET_PROPERTY_VALUE',
payload: {
property,
value,
}
} );
interface SetPropertyValueAction extends Action {
type : string;
payload : {
property : string[];
value : any;
};
}
I can use this action in my code this way:
setPropertyValue( ['grid', 'extents'], 100 );
This works, but since there is no type safety in the setPropertyValue function there is nothing restricting me from feeding invalid values into the function like this:
setPropertyValue( ['grid', 'size'], 100 ); //invalid since IGridSettings doesn't have a 'size' property
setPropertyValue( ['grid', 'isXY'], -1 ); //value should be a boolean not a number
setPropertyValue( ['selected', 'bodyColor'], '255' ); //value should be a number not a string
Is there a way to rewrite the setPropertyValue function so that it only accepts arguments that are valid for the property name found in AppState. Also the value passed in must correspond to the correct type for the selected property.
Perhaps using a string array for the property to change is not ideal but I don't know of a better way to target only the properties that are available in AppState.
If you need the index signature then there is no way to validate the keys of the type (since after all the index signature would mean the class in indexable by any key, so any key would be valid)
To validate taht a string is a key of a type we can use the
keyof
operator, in conjuction with some generic type parameters (to capture the actual key passed in)