Utilizing an API that returns a base type, I employ the as
keyword to convert the type into a union consisting of two sub-types of the original base type.
interface base { a: number; }
interface sub1 extends base { s1: number; }
interface sub2 extends base { s2: number; }
interface sub3 extends base { s3: number; }
declare function returns1or2(): base;
const x = returns1or2() as sub1 | sub2;
console.log(x.a);
This approach works effectively and aligns with my requirements.
However, there is a potential issue with the AsExpression
in this scenario. If the declaration of the API changes to include --strictNullChecks
, the return type may become:
declare function returns1or2(): base | undefined;
const x = returns1or2() as sub1 | sub2;
console.log(x.a); // triggering a run-time error in certain cases
Such changes do not result in compile-time errors for me as the API user, leading to concerns about using the AsExpression
. Are there alternative patterns or strategies that I should consider?