In my app, there is a type called PiiType that enforces strong typing:
type PiiType = 'name' | 'address' | 'email';
When receiving potentially sensitive information from the server, we need to verify if it aligns with this defined type.
A solution proposed on Stack Overflow suggests creating a duplicate array of valid values and checking against it:
isValidPii(value: string): Boolean {
const piiTypeValues = ['name', 'address', 'email'];
return piiTypeValues.indexOf(potentialValue) !== -1;
}
This method is not ideal as it involves defining the type twice, which can lead to errors. Is there a way to check the validity of a value without duplicating its definition?
If there was an operator like isoftype
, the validation process could be simplified:
'name' isoftype PiiType; // true
'hamburger' isoftype PiiType; // false
100 isoftype PiiType; // false
Since such an operator doesn't exist, what alternative approach can be taken to validate a value against this union type?
We are considering using enums instead of native types for representing this typing, but would like to explore other options first.