Currently, I am diving into the concept of type assertion in typescript. Despite going through various resources like the official documentation, an older version, and other articles such as this one, I still find myself puzzled about how typescript validates type assertions as valid.
To illustrate my confusion, consider the following example:
I have defined several types in my code:
type typA = {
name: string;
};
type typB = {
name: string;
age: number;
};
type typC = {
isGraduated: boolean;
};
type typD = {
address: string;
age: number;
};
type typEmpty = {};
Next, I have declared variables with the above-defined types:
let a: typA = {
name: "John",
};
let b: typB = {
name: "Alex",
age: 10,
};
The issue arises when I execute the following code snippets:
a as typEmpty; // (1) Ok
b as typEmpty; // (2) Ok
a as typB; // (3) Ok
b as typA; // (4) Ok
b as typC; // (5) error: ts(2352) Conversion of type '...' to type '...' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first.
b as typD; // (6) error: ts(2352) Conversion of type '...' to type '...' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first.
1 as string // (7) error: ts(2352) Conversion of type '...' to type '...' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first.
b as never as typC; // (8) suprisingly, Ok
b as unknown as typC; // (9) suprisingly, Ok
b as any as typC; // (10) suprisingly, Ok
1 as never as string // (11) suprisingly, Ok
I am left wondering why (8), (9), (10), and (11) are marked as Ok while (5), (6), and (7) throw errors. Any insights would be greatly appreciated!
I've done extensive research before posting this query here, but unfortunately, I haven't been able to find satisfactory explanations yet.
Thank you for mulling over my seemingly foolish question.