Difference from similar question
In error TS2339: Property 'x' does not exist on type 'Y', the subject was the indexable type. Here is not, so most likely the other solutions required.
Problem
interface INumberPropertySpecification__CommonParameters {
readonly type: PROPERTIES_TYPES.NUMBER; // enum
readonly numberType: NUMBER_TYPES; // enum
}
export type NumberPropertySpecification =
INumberPropertySpecification__Required |
INumberPropertySpecification__HasDefault |
INumberPropertySpecification__Optional;
In above code, type NumberPropertySpecification
is the union for below cases:
- The property is required. In this case, library user MUST comprehend it, so I make him to explicitly specify
required: true
interface INumberPropertySpecification__Required extends INumberPropertySpecification__CommonParameters {
readonly required: true;
readonly invalidValueSubstitution?: number;
}
// Example:
const requiredNumberPropertySpecification: INumberPropertySpecification__Required = {
type: PROPERTIES_TYPES.NUMBER,
numberType: NUMBER_TYPES.ANY_REAL_NUMBER,
required: true // user MUST comprehend it, so I make him to explicitly specify it
}
- The property has default value; it means that it is not required. I don't want to make user to specify
required: false
because it's obviously.
interface INumberPropertySpecification__HasDefault extends INumberPropertySpecification__CommonParameters {
readonly defaultValue: number;
}
// Example
const requiredNumberPropertySpecification: INumberPropertySpecification__HasDefault = {
type: PROPERTIES_TYPES.NUMBER,
numberType: NUMBER_TYPES.ANY_REAL_NUMBER,
default: 1
}
- The property is optional. In this case, user MUST comprehend it, so I make him to explicitly specify
required: false
:
interface INumberPropertySpecification__Optional extends INumberPropertySpecification__CommonParameters {
readonly required: false;
}
// Example:
const requiredNumberPropertySpecification: INumberPropertySpecification__Optional = {
type: PROPERTIES_TYPES.NUMBER,
numberType: NUMBER_TYPES.ANY_REAL_NUMBER,
required: false // user MUST comprehend it, so I make him to explicitly specify it
}
Errors
We can not check targetPropertySpecification.required === true
. In this case, TypeScript type check algorithm makes overkill, because when targetPropertySpecification.required
is undefined, no JavaScript error will occur (even if just if(targetPropertySpecification.required)
, but who uses "@typescript-eslint/strict-boolean-expressions":
can not write such as).
Same song with defaultValue
(the isUndefined
):