If I am looking to verify the length of a string in two different ways (either fixed or within a specific range), I can do so using the following examples:
/* Fixed check */
check('abc', {length: 1}); // false
check('abc', {length: 3}); // true
/* Range check */
check('xyz', {minLength: 5, maxLength: 10}); // false
check('xyz', {minLength: 1, maxLength: 10}); // true
check('xyz', {minLength: 3, maxLength: 3}); // true
To achieve this, I have defined two interfaces initially:
interface StringFixed {
length: number;
}
interface StringRange {
minLength: number;
maxLength: number;
}
Next step is to create the function implementation:
function check(value: string, schema: StringFixed): boolean;
function check(value: string, schema: StringRange): boolean;
function check(value: string, schema: StringFixed | StringRange): boolean {
if (typeof schema.length !== 'undefined') { // ERROR
// Implementing fixed length check logic
} else {
// Implementing range check logic
}
}
However, TypeScript raises an error at runtime on the line with 'length' property access:
TS2339: Property 'length' does not exist on type 'StringFix | StringRange'
How can I rectify this issue and successfully execute this code in TypeScript?