How can you restrict keys on an object in TypeScript?
In the code snippet below, I am trying to generate a TypeScript error if any key or value in the object passed to a function is found in my DIMENSIONS
object.
I have been able to trigger an error for values, but I haven't had success with restricting keys.
const DIMENSIONS = {
userType: 1,
moduleVersion: 2
} as const;
type DimensionKeys = keyof typeof DIMENSIONS;
type DimensionValues = typeof DIMENSIONS[DimensionKeys];
type x = typeof DIMENSIONS;
function process<T extends string, V extends number>(yourDimensions: Record<Exclude<T, DimensionKeys>, Exclude<V,DimensionValues>>){
return {...yourDimensions, ...DIMENSIONS};
}
// ----------------------------------------------
// Excellent, carry on
// ----------------------------------------------
const myCorrectDimensions = {
country: 33
} as const;
const combinedDimensions = process(myCorrectDimensions);
// ----------------------------------------------
// Oops, that value is reserved
// ----------------------------------------------
const myInvalidValueDimensions = {
country: 1
} as const;
const badDimensions = process(myInvalidValueDimensions);
// ----------------------------------------------
// Oops, that key is reserved
// ----------------------------------------------
const myInvalidKeyDimensions = {
userType: 79
} as const;
const badDimensions2 = process(myInvalidKeyDimensions);