There is a difference in syntax between using test
and the use of test2
and test3
. For example:
let test: number[] = [1, 2, 3, 'a']
This specifies that the type of test
should be number[]
. However, the array assigned to it does not match that type, resulting in failure.
The second and third examples involve type assertion, done with <>
or as
. This tells TypeScript that you are confident about the type of an expression even if the compiler cannot infer it from the context.
For instance, this code is valid:
const something = localStorage.foobar as number;
or
const something = <number> localStorage.foobar;
even though localStorage's foobar
property may not actually be a number. Type assertion allows you to specify the type regardless of TS inference, rather than checking the type.
The error in the second example involving test2
is due to insufficient overlap between the types string[]
and number[]
.
In contrast, test3
passes because Array<number | string>
can overlap with Array<number>
.
To ensure both test2 and test3 fail as intended, revert to the initial syntax used in the first example by specifying the type after the variable name with a colon:
let test3: {
demo: number;
items: number[];
} = {
demo: 1,
items: [1, 2, 3, 'a'], // This fails - good!
}
This way, TypeScript will properly check the type, leading to a typing error without any type assertion.