When it comes to OK
having no data, the approach I would take is as follows (including an example for usage/checking).
The compiler is able to determine the type based on the value in result
.
I have defined the individual types separately, but they could also be declared inline within the Validation
declaration if preferred (keep them separate if you need explicit references).
type ValidationResult = 'OK' | 'MISSING_FIELDS' | 'DUPLICATED_FIELD';
type ValidationResultOkDetails = null;
type ValidationResultMissingFieldsDetails = [string];
type ValidationResultDuplicatedField = string;
type ValidationOK = {
result: 'OK',
}
type validationMissing = {
result: 'MISSING_FIELDS',
details: ValidationResultMissingFieldsDetails,
}
type validationDuplicated = {
result: 'DUPLICATED_FIELD',
details: ValidationResultDuplicatedField,
}
type Validation = ValidationOK | validationMissing | validationDuplicated;
const ok: Validation = {
result: 'OK',
}
const missing: Validation = {
result: 'MISSING_FIELDS',
details: ['x'],
}
const duplicated: Validation = {
result: 'DUPLICATED_FIELD',
details: 'hello',
}
function handle(v: Validation) {
if (v.result === 'OK') {
// no details
} else if (v.result === 'MISSING_FIELDS') {
// [string]
const m = v.details[0];
} else if (v.result === 'DUPLICATED_FIELD') {
// string
const d = v.details;
}
}
TypeScript Playground